@gitkraken/provider-apis 0.42.0 → 0.43.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/dist/index.js +180 -179
- package/dist/index.providers.js +180 -179
- package/dist/providers/azureDevops/azureDevOps.d.ts +13 -1
- package/dist/types/internalTypes/azureDevOps.d.ts +66 -0
- package/package.json +3 -1
package/dist/index.providers.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
"use strict";var Me=Object.defineProperty;var Sr=Object.getOwnPropertyDescriptor;var vr=Object.getOwnPropertyNames;var qr=Object.prototype.hasOwnProperty;var Er=(r,s)=>{for(var e in s)Me(r,e,{get:s[e],enumerable:!0})},Cr=(r,s,e,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of vr(s))!qr.call(r,n)&&n!==e&&Me(r,n,{get:()=>s[n],enumerable:!(t=Sr(s,n))||t.enumerable});return r};var Lr=r=>Cr(Me({},"__esModule",{value:!0}),r);var en={};Er(en,{AzureDevOps:()=>K,Bitbucket:()=>X,BitbucketServer:()=>Z,EntityIdentifierProviderType:()=>Pr,EntityType:()=>yr,EntityVersion:()=>br,GitBuildStatusStage:()=>Et,GitBuildStatusState:()=>ce,GitDiffLineType:()=>ze,GitHub:()=>Y,GitHubIssueCloseReason:()=>wr,GitIssueState:()=>be,GitLab:()=>te,GitMergeStrategy:()=>V,GitPullRequestMergeableState:()=>W,GitPullRequestReviewState:()=>j,GitPullRequestState:()=>H,GraphQLErrors:()=>h,Jira:()=>re,JiraServer:()=>se,PullRequestAsyncStatus:()=>Ir,Trello:()=>ne,default:()=>Ys,isFetch:()=>ge});module.exports=Lr(en);var Et=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(Et||{}),ce=(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))(ce||{}),V=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(V||{}),H=(t=>(t.Open="OPEN",t.Closed="CLOSED",t.Merged="MERGED",t))(H||{}),j=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(j||{}),W=(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))(W||{}),ze=(t=>(t.ADDED="ADDED",t.DELETED="DELETED",t.UNMODIFIED="UNMODIFIED",t))(ze||{});var Ct={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},G=r=>!r||r.length===0?null:r.reduce((s,e)=>Ct[e.state]>Ct[s]?e.state:s,"APPROVED");var S=100;var Lt=globalThis.fetch;var Dr=async r=>{let s=r.headers.get("content-type")||"",e=null;if(s.startsWith("application/json")){let o=await r.text();e=o.trim().length>0?JSON.parse(o):null}else if(s.startsWith("text/")||s==="")e=await r.text();else if(s.startsWith("application/vnd.github.raw+json"))e=await r.arrayBuffer();else throw new Error(`Unsupported content-type: ${s}`);let t={};r.headers.forEach((o,i)=>{t[i]=o});let n={body:e,headers:t,status:r.status,statusText:r.statusText};if(!r.ok){let o=new Error(r.statusText);throw Object.assign(o,{response:n}),o}return n},He=r=>async({url:s,...e})=>{let t=await r(s,e);return Dr(t)};var ge=(r,s=!1)=>r.name==="fetch"||s;var U=class{constructor(s){let e=s?.request||Lt;this.config={...s,request:ge(e,s?.forceIsFetch)?He(e):e}}updateConfig(s){this.config={...this.config,...s,request:s.request&&ge(s.request,s?.forceIsFetch??this.config.forceIsFetch)?He(s.request):this.config.request}}},D=class extends U{};var R=(r,s)=>{let e={};return r&&(e.Authorization=`${s?"Basic":"Bearer"} ${r}`),e},Dt=r=>r?r.reduce((s,e)=>(s[e]=!0,s),{}):void 0,B=(r,s,e)=>!r||s.some(t=>r[t])?e:"",$t=async r=>{let s=[],e=!0,t;for(;e;){let n=await r(t);s=s.concat(n.data),e=!!n?.pageInfo?.hasNextPage,t=n?.pageInfo?.endCursor||n?.pageInfo?.nextPage}return s};async function We(r){return(await Promise.allSettled(r)).map(e=>$r(e)).filter(e=>e!=null)}function $r(r,s=void 0){return r?.status==="fulfilled"?r.value:s}var Ur="https://app.vssps.visualstudio.com/_apis",Ar="https://vssps.dev.azure.com/",Gr="https://dev.azure.com",P=(r,s={})=>R(s.token||r.token,s.isPAT||r.isPAT),Ut=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/"),Je=(r,s)=>{let e=s.baseUrl||r.baseUrl||Ur;return e=e.replace(/\/$/,""),e},w=(r,s)=>{let e=s.baseUrl||r.baseUrl||Gr;return e=e.replace(/\/$/,""),e},Ve=(r,s)=>{let e=s.baseUrl||r.baseUrl||Ar;return e=e.replace(/\/$/,""),e};var Tr={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},Or={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},Ke=r=>({id:r.id,name:r.displayName??null,username:(r.uniqueName||r.displayName)??null,email:null,avatarUrl:r.imageUrl??null,url:null}),he=r=>r.startsWith("refs/heads/")?r.replace("refs/heads/",""):r,xr=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"}},me=(r,s)=>{let e=[],t=[];return s.reviewers.forEach(n=>{let o={reviewer:Ke(n),state:Or[n.vote??0]||"REVIEW_REQUESTED"};n.isRequired&&e.push(o),t.push(o)}),{id:s.pullRequestId.toString(),title:s.title,description:s.description??null,number:s.codeReviewId,state:Tr[s.status],isDraft:s.isDraft,commentCount:null,upvoteCount:null,author:Ke(s.createdBy),createdDate:new Date(s.creationDate),updatedDate:new Date(s.closedDate||s.creationDate),closedDate:s.closedDate?new Date(s.closedDate):null,mergedDate:s.closedDate&&s.status==="completed"?new Date(s.closedDate):null,repository:{id:s.repository.id,name:s.repository.name,project:s.repository.project.name,owner:{login:r},remoteInfo:null},headCommit:{buildStatuses:null},baseRef:{name:he(s.targetRefName),oid:s.lastMergeTargetCommit.commitId},headRef:{name:he(s.sourceRefName),oid:s.lastMergeSourceCommit.commitId},url:Ut(s),assignees:s.reviewers.map(Ke),reviews:t,reviewDecision:G(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:s.forkSource?{id:s.forkSource.repository.id,name:s.forkSource.repository.name,project:void 0,owner:{login:r},remoteInfo:null}:{id:s.repository.id,name:s.repository.name,project:s.repository.project.name,owner:{login:r},remoteInfo:null},mergeableState:xr(s.mergeStatus),labels:s.labels?.map(n=>({color:null,description:null,id:n.id,name:n.name}))??[],permissions:null}},At=(r,s)=>({id:s.id,name:s.name,namespace:r,project:s.project.name,projectId:s.project.id,webUrl:s.webUrl,httpsUrl:s.remoteUrl,sshUrl:s.sshUrl,defaultBranch:s.defaultBranch?{name:he(s.defaultBranch)}:null,permissions:null}),kr=(r,s,e,t)=>{let n=e.fields,o=n["System.AssignedTo"],i=n["System.State"],a=n["System.WorkItemType"],u;return i&&a&&(u=t[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:n["System.Title"],commentCount:n["System.CommentCount"],author:{avatarUrl:n["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:n["System.CreatedBy"].id,name:n["System.CreatedBy"].uniqueName??null,username:n["System.CreatedBy"].displayName??null,url:null},closedDate:n["Microsoft.VSTS.Common.ClosedDate"]?new Date(n["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(n["System.CreatedDate"]),updatedDate:new Date(n["System.ChangedDate"]),url:e._links.html.href,assignees:o?[{avatarUrl:o._links?.avatar?.href??null,email:null,id:o.id,name:o.uniqueName??null,username:o.displayName??null,url:null}]:[],description:n["System.Description"]??null,state:{name:u?.title||i,color:null},type:n["System.WorkItemType"],repository:null,project:{namespace:r,name:s,resourceId:null,key:null,id:null},upvoteCount:0,labels:e.fields["System.Tags"]?.split(";").map(l=>({color:null,description:null,id:null,name:l.trim()}))??[]}},K=class extends D{async getCurrentUser(s={},e={}){if(e.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let t=`${Je(this.config,e)}/profile/profiles/me`,n=await this.config.request({url:t,headers:P(this.config,e)});return{data:{id:n.body.id,name:n.body.displayName,username:n.body.displayName,email:n.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(s,e={}){let n=(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/_apis/ConnectionData`,headers:P(this.config,e)})).body.authorizedUser;if(n.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:n.id,name:n.providerDisplayName,username:n.providerDisplayName,email:n.properties.Account.$value,avatarUrl:null,url:null}}}async getUserForCommit(s,e={}){if(!s.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(s.repo.namespace)}/${encodeURIComponent(s.repo.project)}/_apis/git/repositories/${encodeURIComponent(s.repo.name)}/commits/${s.oid}`,headers:P(this.config,e)})).body.author;return{data:{name:n.name,email:n.email,avatarUrl:n.imageUrl}}}async getOrgsForUser(s,e={}){let t=`${Je(this.config,e)}/accounts?memberId=${s.userId}&api-version=6.0`;return{data:(await this.config.request({url:t,headers:P(this.config,e)})).body.value.map(o=>({id:o.accountId,name:o.accountName}))}}async getCollectionsForUser(s,e={}){let t=`${w(this.config,e)}/_apis/projectCollections`;return{data:(await this.config.request({url:t,headers:P(this.config,e)})).body.value.map(o=>({id:o.id,name:o.name}))}}async getAzureProjects(s,e={}){let t=new URL(`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/_apis/projects`);t.searchParams.set("$top",S.toString()),s.cursor&&t.searchParams.set("$skip",s.cursor);let n=await this.config.request({url:t.toString(),headers:P(this.config,e)}),o=n.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!o,endCursor:o||null},data:n.body.value.map(i=>({id:i.id,name:i.name,namespace:s.namespace}))}}async getAzureProjectScopeDescriptor(s,e={}){let{namespace:t,projectId:n}=s;return{data:{scope:(await this.config.request({url:`${Ve(this.config,e)}/${encodeURIComponent(t)}/_apis/graph/descriptors/${n}?api-version=6.0`,headers:P(this.config,e)})).body.value}}}async getAzureGraphAccountsForAzureProject(s,e={}){let{namespace:t,projectScopeDescriptor:n,cursor:o}=s,i=new URL(`${Ve(this.config,e)}/${encodeURIComponent(t)}/_apis/graph/users`);n&&i.searchParams.set("scopeDescriptor",n),o&&i.searchParams.set("continuationToken",o);let a=await this.config.request({url:i.toString(),headers:P(this.config,e)}),u=a.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:u||null,hasNextPage:!!u},data:a.body.value.map(l=>({avatarUrl:l._links?.avatar?.href??null,descriptor:l.descriptor??null,email:l.mailAddress??null,name:l.displayName??null,storageKeyURL:l._links?.storageKey?.href??null,username:l.displayName??null}))}}async getAccountFromAzureGraphAccount(s,e={}){let{azureGraphAccount:t}=s;if(!t.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let n=await this.config.request({url:t.storageKeyURL,headers:P(this.config,e)});return{data:{avatarUrl:t.avatarUrl,email:t.email,id:n.body.value,name:t.name,username:t.username,url:null}}}async getAccountsFromAzureGraphAccounts(s,e={}){let t=[];for(let n of s.azureGraphAccounts){let o=await this.getAccountFromAzureGraphAccount({azureGraphAccount:n},e);t.push(o.data)}return{data:t}}async getRepo(s,e={}){if(!s.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let t=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/git/repositories/${encodeURIComponent(s.name)}`,headers:P(this.config,e)});return{data:At(s.namespace,t.body)}}async getRepos(s,e={}){let t=[],n=[];return await Promise.all(s.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:t,errors:n}}async getReposForAzureProject(s,e={}){if(!s.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/git/repositories`,headers:P(this.config,e)})).body.value.map(n=>At(s.namespace,n))}}async getRefs(s,e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=new URL(`${w(this.config,t)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/refs`);n.searchParams.set("filter",s),n.searchParams.set("$top",S.toString()),e.cursor&&n.searchParams.set("continuationToken",e.cursor);let o=await this.config.request({url:n.toString(),headers:P(this.config,t)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({name:he(a.name),commit:{oid:a.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(s,e={}){return this.getRefs("heads",s,e)}async getTags(s,e={}){return this.getRefs("tags",s,e)}async getPullRequestsForRepoBase(s,e={},t=100){let{page:n,repo:o,assigneeLogins:i,authorLogin:a}=s||{},u=n||1;if(!o.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let l="searchCriteria.status=1";return i&&i.length&&(l+=`&searchCriteria.reviewerId=${i[0]}`),a&&(l+=`&searchCriteria.creatorId=${a}`),await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(o.namespace)}/${encodeURIComponent(o.project||"")}/_apis/git/repositories/${encodeURIComponent(o.name)}/pullRequests?${l}&%24top=${t}&%24skip=${(u-1)*t}`,headers:P(this.config,e)})}async getPullRequestsForRepo(s,e={}){let n=s.page||1,o=await this.getPullRequestsForRepoBase(s,e,100);return{pageInfo:{hasNextPage:o.body.value.length===100,nextPage:n+1},data:o.body.value.map(i=>me(s.repo.namespace,i))}}async getPullRequestsForRepos(s,e={}){if(!s.repos.every(o=>o.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:t}=s||{},n=[];return await Promise.all(t.map(async o=>{try{(await this.getPullRequestsForRepoBase({repo:o,...s},e)).body.value.forEach(a=>{n.push(me(o.namespace,a))})}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getPullRequestsForProjectBase(s,e={},t=100){let{namespace:n,project:o,page:i,assigneeLogins:a,authorLogin:u,repo:l}=s;if(l?.project&&l.project!==o)throw new Error("Could not fetch pull requests, project mismatch");let p=i||1,d=new URL(`${w(this.config,e)}/${encodeURIComponent(n)}/${encodeURIComponent(o)}/_apis/git/pullRequests`);return d.searchParams.set("searchCriteria.status","1"),d.searchParams.set("$top",t.toString()),d.searchParams.set("$skip",((p-1)*t).toString()),l?.id&&l?.project===o&&d.searchParams.set("searchCriteria.repositoryId",l.id),a&&a.length&&d.searchParams.set("searchCriteria.reviewerId",a[0]),u&&d.searchParams.set("searchCriteria.creatorId",u),await this.config.request({url:d.toString(),headers:P(this.config,e)})}async getPullRequestsForProject(s,e={}){let n=s.page||1,o=await this.getPullRequestsForProjectBase(s,e,100);return{pageInfo:{hasNextPage:o?.body.value.length===100,nextPage:n+1},data:o?.body.value.map(i=>me(s.namespace,i))||[]}}async getPullRequestsForProjects(s,e={}){let{projects:t}=s||{},n=[];return await Promise.all(t.map(async o=>{try{(!s.repo||s.repo.project&&s.repo.project===o.project)&&(await this.getPullRequestsForProjectBase({...o,...s},e))?.body.value.forEach(a=>{n.push(me(o.namespace,a))})}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getAzurePullRequestLastMergeStatus(s,e={}){if(!s.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:t,project:n,name:o},pullRequestId:i}=s,a=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t)}/${encodeURIComponent(n||"")}/_apis/git/repositories/${o}/pullrequests/${i}?includeCommits=true?api-version=6.0`,headers:{...P(this.config,e)}});if(!a.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:a.body.mergeStatus}}async updatePullRequest(s,e,t){return await this.config.request({method:"PATCH",url:`${w(this.config,t)}/${encodeURIComponent(s.repository.owner.login)}/${encodeURIComponent(s.repository.project)}/_apis/git/repositories/${s.repository.name}/pullrequests/${s.id}?api-version=6.0`,body:e,headers:{...P(this.config,t),"Content-Type":"application/json"}})}async closePullRequest(s,e={}){let{pullRequest:t}=s,n={status:"abandoned"};if(!(await this.updatePullRequest(t,JSON.stringify(n),e)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(s,e={}){let{pullRequest:t,mergeStrategy:n}=s,o;switch(n){case"MERGE_COMMIT":{o="noFastForward";break}case"REBASE":{o="rebase";break}case"REBASE_THEN_MERGE_COMMIT":{o="rebaseMerge";break}case"SQUASH":{o="squash";break}}let i={completionOptions:{mergeStrategy:o},lastMergeSourceCommit:{commitId:t.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(t,JSON.stringify(i),e)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(s,e={}){let{pullRequest:t,label:n}=s;if(!t.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o={name:n.name};if(!(await this.config.request({method:"POST",url:`${w(this.config,e)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/labels?api-version=6.0`,body:JSON.stringify(o),headers:{...P(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(s,e={}){let{pullRequest:t,label:n}=s;if(!t.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${w(this.config,e)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/labels/${encodeURIComponent(n.name)}?api-version=6.0`,headers:{...P(this.config,e)}})}async setPullRequestLabels(s,e={}){let{pullRequest:t,labels:n}=s;if(!t.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=t.labels;if(!o)throw new Error('Azure DevOps requires "labels" for this function.');for(let i of n)o.find(a=>a.id===i.id)||await this.addPullRequestLabel({pullRequest:t,label:i},e);for(let i of o)n.find(a=>i.id===a.id)||await this.removePullRequestLabel({pullRequest:t,label:i},e)}async setPullRequestAsDraft(s,e={}){let{pullRequest:t,isDraft:n}=s,o={isDraft:n};if(!(await this.updatePullRequest(t,JSON.stringify(o),e)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(s,e={}){let{pullRequest:t,reviewer:n,isRequired:o}=s,i={id:n.id,isRequired:o};if(!(await this.config.request({method:"PUT",url:`${w(this.config,e)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/reviewers/${n.id}?api-version=6.0`,body:JSON.stringify(i),headers:{...P(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(s,e={}){let{pullRequest:t,reviewer:n}=s;await this.config.request({method:"DELETE",url:`${w(this.config,e)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/reviewers/${n.id}?api-version=6.0`,headers:{...P(this.config,e),Accept:"application/json"}})}async setPullRequestReviewers(s,e={}){let{pullRequest:t,reviewers:n}=s;for(let o of n)t.assignees.find(i=>i.id===o.id)||await this.addPullRequestReviewer({pullRequest:t,reviewer:o,isRequired:!0},e);for(let o of t.assignees)n.find(i=>o.id===i.id)||await this.removePullRequestReviewer({pullRequest:t,reviewer:o},e)}async getIssuesForAzureProject(s,e={}){let{page:t,assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,statusByWorkItemIdByStatusId:u}=s||{},l=t||1,p=200,d=["[Microsoft.VSTS.Common.ClosedDate] = ''","[System.TeamProject] = @project","[Microsoft.VSTS.Common.ResolvedDate] = ''"];o&&d.push(`[System.CreatedBy] = '${o.replace("'","''")}'`),n&&n[0]&&d.push(`[System.AssignedTo] = '${n[0].replace("'","''")}'`),i&&d.push("[System.Id] IN (@recentMentions)"),a&&a.forEach(I=>d.push(`[System.Tags] Contains '${I}'`));let c=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${d.join(" AND ")} order by [System.CreatedDate] desc`,g=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:c}),method:"POST",headers:{...P(this.config,e),"Content-Type":"application/json"}}),m=g.body.workItems.slice((l-1)*p,p*l).map(I=>I.id);if(m.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let b=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:m,$expand:"Links"}),method:"POST",headers:{...P(this.config,e),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:g.body.workItems.length>p*l,nextPage:l+1},data:b.body.value.map(I=>kr(s.namespace,s.project,I,u||{}))}}async getPermissionsForRepos(s,e={}){let{namespace:t,repos:n}=s,o={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},i=p=>{let d="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",c=`repoV2/${p.projectId}/${p.id}`;return Object.keys(o).map(g=>({securityNamespaceId:d,token:c,permissions:g}))},a={alwaysAllowAdministrators:!1,evaluations:n.flatMap(i)};return{data:(await this.config.request({method:"POST",url:`${w(this.config,e)}/${encodeURIComponent(t)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(a),headers:{...P(this.config,e),"Content-Type":"application/json"}})).body.evaluations.reduce((p,d)=>{let[,c,g]=d.token.split("/"),m=`${c}/${g}`,b=o[d.permissions];for(let I of b)p[m]===void 0&&(p[m]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),d.value===!1&&(p[m][I]=!1);return p},{})}}async decorateReposWithPermissions(s,e={}){let{namespace:t,repos:n}=s,o=await this.getPermissionsForRepos({namespace:t,repos:n},e);return{data:n.map(i=>({...i,permissions:o.data[`${i.projectId}/${i.id}`]}))}}async updateIssue(s,e,t={}){return await this.config.request({method:"PATCH",url:`${w(this.config,t)}/${encodeURIComponent(s.project.namespace)}/${encodeURIComponent(s.project.name)}/_apis/wit/workitems/${s.id}?api-version=6.0`,body:JSON.stringify(e),headers:{...P(this.config,t),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(s,e={}){let{issue:t,status:n}=s,o=[{op:"add",path:"/fields/System.State",value:n.name}];if(!(await this.updateIssue(t,o,e)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(s,e={}){let{issue:t,assignee:n}=s,o=[{op:"add",path:"/fields/System.AssignedTo",value:n?.name??""}];if(!(await this.updateIssue(t,o,e)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(s,e={}){let{issue:t,labels:n}=s,i=[{op:"replace",path:"/fields/System.Tags",value:n.map(u=>u.name).join(";")}];if(!(await this.updateIssue(t,i,e)).body.fields?.["System.Tags"])throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(s,e={}){if(!s.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:t,project:n}=s;return{data:(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t)}/${encodeURIComponent(n||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...P(this.config,e)}})).body.value}}async getLabelsForProject(s,e={}){let{namespace:t,project:n}=s;return{data:(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t)}/${encodeURIComponent(n||"")}/_apis/wit/tags?api-version=6.0`,headers:{...P(this.config,e)}})).body.value.map(i=>({color:null,description:null,id:i.id,name:i.name,url:i.url}))}}};var q=(r,s={})=>R(s.token||r.token,s.isPAT||r.isPAT);var E="https://api.bitbucket.org/2.0",Nr={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},fe={owner:4,admin:3,contributor:2,member:1},Re=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}),Gt=r=>{let s=r.links.clone,e=s?.find(n=>n.name==="ssh"),t=s?.find(n=>n.name==="https");return e&&t?{cloneUrlHTTPS:t.href,cloneUrlSSH:e.href}:null},Xe=r=>({id:r.uuid,namespace:r.workspace.slug,name:r.slug,webUrl:r.links.html.href,httpsUrl:r.links.clone.find(s=>s.name==="https")?.href??null,sshUrl:r.links.clone.find(s=>s.name==="ssh")?.href??null,defaultBranch:{name:r.mainbranch.name},permissions:null}),Ze=r=>{let s=r.id,e=r.participants?.map(t=>{let n="REVIEW_REQUESTED";return t.approved?n="APPROVED":t.state==="changes_requested"?n="CHANGES_REQUESTED":t.participated_on!==null&&(n="COMMENTED"),{reviewer:Re(t.user),state:n}})??[];return{id:s.toString(),title:r.title,description:r.description,number:s,state:Nr[r.state],isDraft:!1,commentCount:r.comment_count,upvoteCount:null,author:Re(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:Gt(r.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:r.destination.branch.name,oid:r.destination.commit.hash},headRef:{name:r.source.branch.name,oid:r.source.commit.hash},url:r.links.html.href,assignees:null,reviews:e,reviewDecision:G(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:{id:r.source.repository.uuid,name:r.source.repository.name,owner:{login:r.source.repository.full_name.split("/")[0]},remoteInfo:Gt(r.source.repository)},mergeableState:"MERGEABLE",permissions:null}},_r=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}}},Fr=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}}},X=class extends U{async refreshToken(s){return{data:(await this.config.request({url:"https://bitbucket.org/site/oauth2/access_token",method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Basic ${s.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${s.refreshToken}`})).body}}async getCurrentUser(s={},e={}){let t=await this.config.request({url:`${E}/user`,headers:q(this.config,e)});return{data:Re(t.body)}}async getUserForCommit(s,e={}){let n=(await this.config.request({url:`${E}/repositories/${s.repo.namespace}/${s.repo.name}/commit/${s.oid}`,headers:q(this.config,e)})).body.author,o=n.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:n.user?.links.avatar.href||null}}}async getRepo(s,e={}){let t=await this.config.request({url:`${E}/repositories/${s.namespace}/${s.name}`,headers:q(this.config,e)});return{data:Xe(t.body)}}async getRepos(s,e={}){let t=[],n=[];return await Promise.all(s.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:t,errors:n}}async getReposForWorkspace(s,e={}){let t=new URL(`${E}/repositories/${encodeURIComponent(s.workspace)}`);t.searchParams.set("page",s.page?.toString()||"1"),t.searchParams.set("pagelen",S.toString()),s.minimumRole&&t.searchParams.set("role",s.minimumRole);let n=await this.config.request({url:t.toString(),headers:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(Xe)}}async getAllReposForWorkspace(s,e={}){let t=[],n=1;for(;n!==null;){let o=await this.getReposForWorkspace({workspace:s.workspace,minimumRole:s.minimumRole,page:n},e);t.push(...o.data),n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}return t}async getAllReposForWorkspaceWithPermissions(s,e={}){let t=new Map,n=[],o=fe[s.minimumRole||"member"];o<=fe.admin&&n.push("admin"),o<=fe.contributor&&n.push("contributor"),o<=fe.member&&n.push("member");let i=[];for(let a of n){i=await this.getAllReposForWorkspace({workspace:s.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:Fr(u)}})}}async getReposForCurrentUser(s,e={}){let t=new URL(`${E}/repositories`);t.searchParams.set("role","member"),t.searchParams.set("pagelen",S.toString()),s.cursor&&t.searchParams.set("after",s.cursor);let n=await this.config.request({url:t.toString(),headers:q(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(Xe)}}async getBranches(s,e={}){let t=new URL(`${E}/repositories/${s.repo.namespace}/${s.repo.name}/refs/branches`);t.searchParams.set("page",s.page?.toString()||"1"),t.searchParams.set("pagelen",S.toString());let n=await this.config.request({url:t.toString(),headers:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>{let a=new Date(i.target.date);return{name:i.name,commit:{oid:i.target.hash,authoredDate:a,committedDate:a}}})}}async getTags(s,e={}){let t=new URL(`${E}/repositories/${s.repo.namespace}/${s.repo.name}/refs/tags`);t.searchParams.set("pagelen",S.toString()),s.cursor&&t.searchParams.set("page",s.cursor);let n=await this.config.request({url:t.toString(),headers:q(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(a=>{let u=new Date(a.target.date);return{name:a.name,commit:{oid:a.target.hash,authoredDate:u,committedDate:u}}})}}async getWorkspacesForCurrentUser(s={},e={}){let t=new URL(`${E}/user/workspaces`);t.searchParams.set("page",s?.page?.toString()||"1"),t.searchParams.set("pagelen","50"),s?.administrator!==void 0&&t.searchParams.set("administrator",s.administrator.toString());let n=await this.config.request({url:t.toString(),headers:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug}))}}async getWorkspacesForUser(s,e={}){let t=new URL(`${E}/user/permissions/workspaces`);t.searchParams.set("page",s.page?.toString()||"1"),t.searchParams.set("pagelen","50");let n=await this.config.request({url:t.toString(),headers:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(s,e={}){let t=new URL(`${E}/workspaces/${s.workspaceSlug}/pullrequests/${s.userId}`);if(t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",s.page?.toString()||"1"),t.searchParams.set("pagelen","50"),s.repos&&s.repos.length>0){let i=`state = "open" AND (${s.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`;t.searchParams.set("q",i)}let n=await this.config.request({url:t.toString(),headers:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(Ze)}}async getPullRequestsForRepoBase(s,e={}){let t=new URL(`${E}/repositories/${encodeURI(s.repo.namespace)}/${encodeURI(s.repo.name)}/pullrequests?state=OPEN`),n=[];s.reviewerId&&n.push(`reviewers.uuid="${s.reviewerId}"`),s.authorLogin&&n.push(`author.uuid="${s.authorLogin}"`);let o='state="OPEN"';return n.length&&(o+=` AND (${n.join(s.useOrFilter?" OR ":" AND ")})`),t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",s.page?.toString()||"1"),t.searchParams.set("pagelen","50"),t.searchParams.set("q",o),await this.config.request({url:t.toString(),headers:q(this.config,e)})}async getPullRequestsForRepo(s,e={}){let t=[],n=await this.getPullRequestsForRepoBase(s,e);n.body.values.forEach(i=>{t.push(Ze(i))});let o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:t}}async getPullRequestsForRepos(s,e={}){let t=[];return await Promise.all(s.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...s},e)).body.values.forEach(i=>{t.push(Ze(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getAccountsForWorkspace(s,e={}){let t=new URL(`${E}/workspaces/${encodeURI(s.workspace)}/members`);t.searchParams.set("page",s.page?.toString()||"1"),t.searchParams.set("pagelen","100");let n=await this.config.request({url:t.toString(),headers:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>Re(i.user))}}async getReposPermissionsForCurrentUser(s,e={}){let t=new URL(`${E}/user/permissions/repositories`);t.searchParams.set("page",s.page?.toString()||"1"),t.searchParams.set("pagelen","100");let n=await this.config.request({url:t.toString(),headers:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.reduce((i,a)=>({...i,[a.repository.uuid]:_r(a.permission)}),{})}}async decorateReposWithPermissions(s,e={}){let t={},n=1;do{let o=await this.getReposPermissionsForCurrentUser({page:n},e);t={...o.data,...t},n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(n!==null);return{data:s.repos.map(o=>({...o,permissions:t[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(s,e={}){let{pullRequest:t}=s;if(!(await this.config.request({method:"POST",url:`${E}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/decline`,headers:q(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(s,e={}){let{pullRequest:t,mergeStrategy:n}=s,o;switch(n){case"MERGE_COMMIT":{o="merge_commit";break}case"FAST_FORWARD":{o="fast_forward";break}case"SQUASH":{o="squash";break}}let i={merge_strategy:o,type:"pullrequest"};if(!(await this.config.request({method:"POST",url:`${E}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/merge`,body:JSON.stringify(i),headers:{...q(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(s,e={}){let{pullRequest:t,reviewers:n}=s,o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket reviewer requires "username" for this function.');return{username:a.username}})};if(!(await this.config.request({method:"PUT",url:`${E}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}`,body:JSON.stringify(o),headers:{...q(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var Tt=r=>r?r.find(s=>s.permission==="USER_ADMIN"||s.permission==="PROJECT_ADMIN"||s.permission==="ADMIN"||s.permission==="SYS_ADMIN"||s.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:r.find(s=>s.permission==="REPO_WRITE"||s.permission==="REPO_CREATE"||s.permission==="PROJECT_CREATE"||s.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var ae=r=>{let s=r.links.self[0].href;return{name:r.displayName,email:r.emailAddress,avatarUrl:r.avatarUrl??(s&&`${s}/avatar.png`),id:r.id.toString(),username:r.name,url:s}},Ie=r=>{let s={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},t=r.reviewers.map(u=>({reviewer:ae(u.user),state:e[u.status]})),n=r.toRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,o=r.toRef.repository.links.clone.find(u=>u.name==="https")?.href??null;o||(o=r.toRef.repository.links.clone.find(u=>u.name==="http")?.href??null);let i=r.fromRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,a=r.fromRef.repository.links.clone.find(u=>u.name==="https")?.href??null;return a||(a=r.fromRef.repository.links.clone.find(u=>u.name==="http")?.href??null),{id:r.id.toString(),number:r.id,title:r.title,description:r.description,url:r.links.self[0].href,state:s[r.state],isDraft:!1,createdDate:new Date(r.createdDate),updatedDate:new Date(r.updatedDate),closedDate:r.closedDate?new Date(r.closedDate):null,mergedDate:r.state=="MERGED"&&r.closedDate?new Date(r.closedDate):null,baseRef:{name:r.toRef.displayId,oid:r.toRef.latestCommit},headRef:{name:r.fromRef.displayId,oid:r.fromRef.latestCommit},commentCount:r.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:ae(r.author.user),assignees:null,reviews:t,reviewDecision:G(t),repository:{id:r.toRef.repository.id.toString(),name:r.toRef.repository.name,owner:{login:r.toRef.repository.project.key},remoteInfo:o&&n?{cloneUrlHTTPS:o,cloneUrlSSH:n}:null},headRepository:{id:r.fromRef.repository.id.toString(),name:r.fromRef.repository.name,owner:{login:r.fromRef.repository.project.key},remoteInfo:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:r.version}},Ot=r=>({id:r.id.toString(),namespace:r.project.key,name:r.slug,webUrl:r.links.self[0]?.href??null,httpsUrl:r.links.clone.find(s=>s.name==="https"||s.name==="http")?.href??null,sshUrl:r.links.clone.find(s=>s.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),Z=class extends D{getBaseUrl(s){let e=s.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(s){return R(s.token||this.config.token)}async getCurrentUser(s={},e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":n,"x-ausername":o}}=t,i=n?parseInt(n,10):null,a=decodeURIComponent(o),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:p,id:d,name:c,slug:g})=>i?i===d:a===c||a===p||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:ae(l)}}async getUserForCommit(s,e){let{repo:t,oid:n}=s,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}/commits/${n}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:ae(o.body.author)}}async getRepo(s,e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${s.namespace}/repos/${s.name}`,headers:this.getRequestHeaders(e)});return{data:Ot(t.body)}}async getRepos(s,e={}){let t=[],n=[];return await Promise.all(s.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:t,errors:n}}async getReposForCurrentUser(s,e={}){let t=s.page??0,n=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${t}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!n.body.isLastPage,nextPage:n.body.nextPageStart},data:n.body.values.map(Ot)}}async getRepoPermissionsForUsername(s,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${s.repo.namespace}/repos/${s.repo.name}/permissions/search?filterText=${s.username}`);try{let n=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)});return{data:Tt(n.body.values)}}catch(n){if(n.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw n}}async decorateReposWithPermissions(s,e={}){return await Promise.all(s.repos.map(async n=>{let o=await this.getRepoPermissionsForUsername({repo:n,username:s.username},e);return{...n,permissions:o.data}}))}async getPullRequestsForRepoBase(s,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(s.repo.namespace)}/repos/${encodeURI(s.repo.name)}/pull-requests?state=OPEN`);return t.searchParams.set("start",s.page?.toString()||"0"),t.searchParams.set("limit","50"),await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(s,e={}){let t=[],n=await this.getPullRequestsForRepoBase(s,e);n.body.values.forEach(i=>{if(s.authorLogin&&i.author.user.name!==s.authorLogin)return null;t.push(Ie(i))});let o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:t}}async getPullRequestsForRepos(s,e={}){let t=[];return await Promise.all(s.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...s},e)).body.values.forEach(i=>{if(s.authorLogin&&i.author.user.name!==s.authorLogin)return null;t.push(Ie(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getPullRequestsForCurrentUser(s,e={}){let t=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);t.searchParams.set("state","OPEN"),t.searchParams.set("start",s.page?.toString()||"0"),t.searchParams.set("limit","50");let n=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(Ie)}}async closePullRequest(s,e={}){let{pullRequest:t}=s;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/decline`,body:JSON.stringify({version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(s,e={}){let{pullRequest:t,mergeStrategyId:n}=s;if(s.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/merge`,body:JSON.stringify({strategyId:n,version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(s={}){let e=await this.config.request({url:`${this.getBaseUrl(s)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(s),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(s,e={}){let{pullRequest:t,reviewers:n}=s;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:a.username}}}),version:t.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}async getAccountsForProject(s,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(s.project)}/permissions/users`);t.searchParams.set("start",s.page?.toString()||"0"),t.searchParams.set("limit","50");let n=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(i=>ae(i.user))}}};var Kt=require("js-base64");var be=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(be||{});var h=class extends Error{constructor(e,t){let n=t?.map(i=>`'${i.message}'`).join(", "),o=n?`${e}: ${n}`:e;super(o);this.graphQLErrors=t??[]}};var Qr={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]},xt=15,kt=100,ue={__typename:"User",id:"U_kgDNJ5k",databaseId:10137,name:"Deleted user",login:"ghost",email:"",avatarUrl:"https://avatars.githubusercontent.com/u/10137?v=4",url:"https://github.com/ghost"},C=r=>!!r,T=(r,s)=>{let e=Qr[s];for(let t=0;t<3;t++){if(r[t]>e[t])return!0;if(r[t]<e[t])return!1}return!0},Pe="https://api.github.com",jr=`${Pe}/graphql`,we=`
|
|
1
|
+
"use strict";var We=Object.defineProperty;var Gr=Object.getOwnPropertyDescriptor;var Tr=Object.getOwnPropertyNames;var Or=Object.prototype.hasOwnProperty;var xr=(r,s)=>{for(var e in s)We(r,e,{get:s[e],enumerable:!0})},kr=(r,s,e,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of Tr(s))!Or.call(r,n)&&n!==e&&We(r,n,{get:()=>s[n],enumerable:!(t=Gr(s,n))||t.enumerable});return r};var Nr=r=>kr(We({},"__esModule",{value:!0}),r);var dn={};xr(dn,{AzureDevOps:()=>ee,Bitbucket:()=>te,BitbucketServer:()=>re,EntityIdentifierProviderType:()=>Cr,EntityType:()=>Er,EntityVersion:()=>qr,GitBuildStatusStage:()=>Ut,GitBuildStatusState:()=>he,GitDiffLineType:()=>Je,GitHub:()=>se,GitHubIssueCloseReason:()=>Lr,GitIssueState:()=>Pe,GitLab:()=>oe,GitMergeStrategy:()=>Y,GitPullRequestMergeableState:()=>V,GitPullRequestReviewState:()=>M,GitPullRequestState:()=>J,GraphQLErrors:()=>h,Jira:()=>ie,JiraServer:()=>ae,PullRequestAsyncStatus:()=>vr,Trello:()=>ue,default:()=>pn,isFetch:()=>fe});module.exports=Nr(dn);var Nt=require("diff");var Ut=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(Ut||{}),he=(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))(he||{}),Y=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(Y||{}),J=(t=>(t.Open="OPEN",t.Closed="CLOSED",t.Merged="MERGED",t))(J||{}),M=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(M||{}),V=(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))(V||{}),Je=(t=>(t.ADDED="ADDED",t.DELETED="DELETED",t.UNMODIFIED="UNMODIFIED",t))(Je||{});var At={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},O=r=>!r||r.length===0?null:r.reduce((s,e)=>At[e.state]>At[s]?e.state:s,"APPROVED");var v=100;var Gt=globalThis.fetch;var _r=async r=>{let s=r.headers.get("content-type")||"",e=null;if(s.startsWith("application/json")){let o=await r.text();e=o.trim().length>0?JSON.parse(o):null}else if(s.startsWith("text/")||s==="")e=await r.text();else if(s.startsWith("application/vnd.github.raw+json")||s.startsWith("application/octet-stream"))e=await r.arrayBuffer();else throw new Error(`Unsupported content-type: ${s}`);let t={};r.headers.forEach((o,i)=>{t[i]=o});let n={body:e,headers:t,status:r.status,statusText:r.statusText};if(!r.ok){let o=new Error(r.statusText);throw Object.assign(o,{response:n}),o}return n},Ve=r=>async({url:s,...e})=>{let t=await r(s,e);return _r(t)};var fe=(r,s=!1)=>r.name==="fetch"||s;var G=class{constructor(s){let e=s?.request||Gt;this.config={...s,request:fe(e,s?.forceIsFetch)?Ve(e):e}}updateConfig(s){this.config={...this.config,...s,request:s.request&&fe(s.request,s?.forceIsFetch??this.config.forceIsFetch)?Ve(s.request):this.config.request}}},$=class extends G{};var R=(r,s)=>{let e={};return r&&(e.Authorization=`${s?"Basic":"Bearer"} ${r}`),e},Tt=r=>r?r.reduce((s,e)=>(s[e]=!0,s),{}):void 0,z=(r,s,e)=>!r||s.some(t=>r[t])?e:"",Ot=async r=>{let s=[],e=!0,t;for(;e;){let n=await r(t);s=s.concat(n.data),e=!!n?.pageInfo?.hasNextPage,t=n?.pageInfo?.endCursor||n?.pageInfo?.nextPage}return s};async function Ke(r){return(await Promise.allSettled(r)).map(e=>Fr(e)).filter(e=>e!=null)}function Fr(r,s=void 0){return r?.status==="fulfilled"?r.value:s}var Qr="https://app.vssps.visualstudio.com/_apis",jr="https://vssps.dev.azure.com/",Br="https://dev.azure.com",y=(r,s={})=>R(s.token||r.token,s.isPAT||r.isPAT),xt=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/"),Xe=(r,s)=>{let e=s.baseUrl||r.baseUrl||Qr;return e=e.replace(/\/$/,""),e},w=(r,s)=>{let e=s.baseUrl||r.baseUrl||Br;return e=e.replace(/\/$/,""),e},Ze=(r,s)=>{let e=s.baseUrl||r.baseUrl||jr;return e=e.replace(/\/$/,""),e};var Mr={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},zr={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},Ye=r=>({id:r.id,name:r.displayName??null,username:(r.uniqueName||r.displayName)??null,email:null,avatarUrl:r.imageUrl??null,url:null}),Re=r=>r.startsWith("refs/heads/")?r.replace("refs/heads/",""):r,Hr=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"}},le=(r,s)=>{let e=[],t=[];return s.reviewers.forEach(n=>{let o={reviewer:Ye(n),state:zr[n.vote??0]||"REVIEW_REQUESTED"};n.isRequired&&e.push(o),t.push(o)}),{id:s.pullRequestId.toString(),title:s.title,description:s.description??null,number:s.codeReviewId,state:Mr[s.status],isDraft:s.isDraft,commentCount:null,upvoteCount:null,author:Ye(s.createdBy),createdDate:new Date(s.creationDate),updatedDate:new Date(s.closedDate||s.creationDate),closedDate:s.closedDate?new Date(s.closedDate):null,mergedDate:s.closedDate&&s.status==="completed"?new Date(s.closedDate):null,repository:{id:s.repository.id,name:s.repository.name,project:s.repository.project.name,owner:{login:r},remoteInfo:null},headCommit:{buildStatuses:null},baseRef:{name:Re(s.targetRefName),oid:s.lastMergeTargetCommit.commitId},headRef:{name:Re(s.sourceRefName),oid:s.lastMergeSourceCommit.commitId},url:xt(s),assignees:s.reviewers.map(Ye),reviews:t,reviewDecision:O(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:s.forkSource?{id:s.forkSource.repository.id,name:s.forkSource.repository.name,project:void 0,owner:{login:r},remoteInfo:null}:{id:s.repository.id,name:s.repository.name,project:s.repository.project.name,owner:{login:r},remoteInfo:null},mergeableState:Hr(s.mergeStatus),labels:s.labels?.map(n=>({color:null,description:null,id:n.id,name:n.name}))??[],permissions:null}},kt=(r,s)=>({id:s.id,name:s.name,namespace:r,project:s.project.name,projectId:s.project.id,webUrl:s.webUrl,httpsUrl:s.remoteUrl,sshUrl:s.sshUrl,defaultBranch:s.defaultBranch?{name:Re(s.defaultBranch)}:null,permissions:null}),Wr=(r,s,e,t)=>{let n=e.fields,o=n["System.AssignedTo"],i=n["System.State"],a=n["System.WorkItemType"],u;return i&&a&&(u=t[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:n["System.Title"],commentCount:n["System.CommentCount"],author:{avatarUrl:n["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:n["System.CreatedBy"].id,name:n["System.CreatedBy"].uniqueName??null,username:n["System.CreatedBy"].displayName??null,url:null},closedDate:n["Microsoft.VSTS.Common.ClosedDate"]?new Date(n["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(n["System.CreatedDate"]),updatedDate:new Date(n["System.ChangedDate"]),url:e._links.html.href,assignees:o?[{avatarUrl:o._links?.avatar?.href??null,email:null,id:o.id,name:o.uniqueName??null,username:o.displayName??null,url:null}]:[],description:n["System.Description"]??null,state:{name:u?.title||i,color:null},type:n["System.WorkItemType"],repository:null,project:{namespace:r,name:s,resourceId:null,key:null,id:null},upvoteCount:0,labels:e.fields["System.Tags"]?.split(";").map(l=>({color:null,description:null,id:null,name:l.trim()}))??[]}},ee=class extends ${getRepoApiUrl(s,e,t,n){return`${w(this.config,n)}/${encodeURIComponent(s)}/${encodeURIComponent(e)}/_apis/git/repositories/${encodeURIComponent(t)}`}async getCurrentUser(s={},e={}){if(e.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let t=`${Xe(this.config,e)}/profile/profiles/me`,n=await this.config.request({url:t,headers:y(this.config,e)});return{data:{id:n.body.id,name:n.body.displayName,username:n.body.displayName,email:n.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(s,e={}){let n=(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/_apis/ConnectionData`,headers:y(this.config,e)})).body.authorizedUser;if(n.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:n.id,name:n.providerDisplayName,username:n.providerDisplayName,email:n.properties.Account.$value,avatarUrl:null,url:null}}}async getUserForCommit(s,e={}){if(!s.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(s.repo.namespace)}/${encodeURIComponent(s.repo.project)}/_apis/git/repositories/${encodeURIComponent(s.repo.name)}/commits/${s.oid}`,headers:y(this.config,e)})).body.author;return{data:{name:n.name,email:n.email,avatarUrl:n.imageUrl}}}async getOrgsForUser(s,e={}){let t=`${Xe(this.config,e)}/accounts?memberId=${s.userId}&api-version=6.0`;return{data:(await this.config.request({url:t,headers:y(this.config,e)})).body.value.map(o=>({id:o.accountId,name:o.accountName}))}}async getCollectionsForUser(s,e={}){let t=`${w(this.config,e)}/_apis/projectCollections`;return{data:(await this.config.request({url:t,headers:y(this.config,e)})).body.value.map(o=>({id:o.id,name:o.name}))}}async getAzureProjects(s,e={}){let t=new URL(`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/_apis/projects`);t.searchParams.set("$top",v.toString()),s.cursor&&t.searchParams.set("$skip",s.cursor);let n=await this.config.request({url:t.toString(),headers:y(this.config,e)}),o=n.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!o,endCursor:o||null},data:n.body.value.map(i=>({id:i.id,name:i.name,namespace:s.namespace}))}}async getAzureProjectScopeDescriptor(s,e={}){let{namespace:t,projectId:n}=s;return{data:{scope:(await this.config.request({url:`${Ze(this.config,e)}/${encodeURIComponent(t)}/_apis/graph/descriptors/${n}?api-version=6.0`,headers:y(this.config,e)})).body.value}}}async getAzureGraphAccountsForAzureProject(s,e={}){let{namespace:t,projectScopeDescriptor:n,cursor:o}=s,i=new URL(`${Ze(this.config,e)}/${encodeURIComponent(t)}/_apis/graph/users`);n&&i.searchParams.set("scopeDescriptor",n),o&&i.searchParams.set("continuationToken",o);let a=await this.config.request({url:i.toString(),headers:y(this.config,e)}),u=a.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:u||null,hasNextPage:!!u},data:a.body.value.map(l=>({avatarUrl:l._links?.avatar?.href??null,descriptor:l.descriptor??null,email:l.mailAddress??null,name:l.displayName??null,storageKeyURL:l._links?.storageKey?.href??null,username:l.displayName??null}))}}async getAccountFromAzureGraphAccount(s,e={}){let{azureGraphAccount:t}=s;if(!t.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let n=await this.config.request({url:t.storageKeyURL,headers:y(this.config,e)});return{data:{avatarUrl:t.avatarUrl,email:t.email,id:n.body.value,name:t.name,username:t.username,url:null}}}async getAccountsFromAzureGraphAccounts(s,e={}){let t=[];for(let n of s.azureGraphAccounts){let o=await this.getAccountFromAzureGraphAccount({azureGraphAccount:n},e);t.push(o.data)}return{data:t}}async getRepo(s,e={}){if(!s.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let t=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/git/repositories/${encodeURIComponent(s.name)}`,headers:y(this.config,e)});return{data:kt(s.namespace,t.body)}}async getRepos(s,e={}){let t=[],n=[];return await Promise.all(s.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:t,errors:n}}async getReposForAzureProject(s,e={}){if(!s.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/git/repositories`,headers:y(this.config,e)})).body.value.map(n=>kt(s.namespace,n))}}async getRefs(s,e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=new URL(`${w(this.config,t)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/refs`);n.searchParams.set("filter",s),n.searchParams.set("$top",v.toString()),e.cursor&&n.searchParams.set("continuationToken",e.cursor);let o=await this.config.request({url:n.toString(),headers:y(this.config,t)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({name:Re(a.name),commit:{oid:a.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(s,e={}){return this.getRefs("heads",s,e)}async getTags(s,e={}){return this.getRefs("tags",s,e)}async getPullRequestsForRepoBase(s,e={},t=100){let{page:n,repo:o,assigneeLogins:i,authorLogin:a}=s||{},u=n||1;if(!o.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let l="searchCriteria.status=1";return i&&i.length&&(l+=`&searchCriteria.reviewerId=${i[0]}`),a&&(l+=`&searchCriteria.creatorId=${a}`),await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(o.namespace)}/${encodeURIComponent(o.project||"")}/_apis/git/repositories/${encodeURIComponent(o.name)}/pullRequests?${l}&%24top=${t}&%24skip=${(u-1)*t}`,headers:y(this.config,e)})}async getPullRequestsForRepo(s,e={}){let n=s.page||1,o=await this.getPullRequestsForRepoBase(s,e,100);return{pageInfo:{hasNextPage:o.body.value.length===100,nextPage:n+1},data:o.body.value.map(i=>le(s.repo.namespace,i))}}async getPullRequestsForRepos(s,e={}){if(!s.repos.every(o=>o.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:t}=s||{},n=[];return await Promise.all(t.map(async o=>{try{(await this.getPullRequestsForRepoBase({repo:o,...s},e)).body.value.forEach(a=>{n.push(le(o.namespace,a))})}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getPullRequestsForProjectBase(s,e={},t=100){let{namespace:n,project:o,page:i,assigneeLogins:a,authorLogin:u,repo:l}=s;if(l?.project&&l.project!==o)throw new Error("Could not fetch pull requests, project mismatch");let p=i||1,d=new URL(`${w(this.config,e)}/${encodeURIComponent(n)}/${encodeURIComponent(o)}/_apis/git/pullRequests`);return d.searchParams.set("searchCriteria.status","1"),d.searchParams.set("$top",t.toString()),d.searchParams.set("$skip",((p-1)*t).toString()),l?.id&&l?.project===o&&d.searchParams.set("searchCriteria.repositoryId",l.id),a&&a.length&&d.searchParams.set("searchCriteria.reviewerId",a[0]),u&&d.searchParams.set("searchCriteria.creatorId",u),await this.config.request({url:d.toString(),headers:y(this.config,e)})}async getPullRequestsForProject(s,e={}){let n=s.page||1,o=await this.getPullRequestsForProjectBase(s,e,100);return{pageInfo:{hasNextPage:o?.body.value.length===100,nextPage:n+1},data:o?.body.value.map(i=>le(s.namespace,i))||[]}}async getPullRequestsForProjects(s,e={}){let{projects:t}=s||{},n=[];return await Promise.all(t.map(async o=>{try{(!s.repo||s.repo.project&&s.repo.project===o.project)&&(await this.getPullRequestsForProjectBase({...o,...s},e))?.body.value.forEach(a=>{n.push(le(o.namespace,a))})}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getAzurePullRequestLastMergeStatus(s,e={}){if(!s.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:t,project:n,name:o},pullRequestId:i}=s,a=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t)}/${encodeURIComponent(n||"")}/_apis/git/repositories/${o}/pullrequests/${i}?includeCommits=true?api-version=6.0`,headers:{...y(this.config,e)}});if(!a.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:a.body.mergeStatus}}async updatePullRequest(s,e,t){return await this.config.request({method:"PATCH",url:`${w(this.config,t)}/${encodeURIComponent(s.repository.owner.login)}/${encodeURIComponent(s.repository.project)}/_apis/git/repositories/${s.repository.name}/pullrequests/${s.id}?api-version=6.0`,body:e,headers:{...y(this.config,t),"Content-Type":"application/json"}})}async closePullRequest(s,e={}){let{pullRequest:t}=s,n={status:"abandoned"};if(!(await this.updatePullRequest(t,JSON.stringify(n),e)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(s,e={}){let{pullRequest:t,mergeStrategy:n}=s,o;switch(n){case"MERGE_COMMIT":{o="noFastForward";break}case"REBASE":{o="rebase";break}case"REBASE_THEN_MERGE_COMMIT":{o="rebaseMerge";break}case"SQUASH":{o="squash";break}}let i={completionOptions:{mergeStrategy:o},lastMergeSourceCommit:{commitId:t.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(t,JSON.stringify(i),e)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(s,e={}){let{pullRequest:t,label:n}=s;if(!t.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o={name:n.name};if(!(await this.config.request({method:"POST",url:`${w(this.config,e)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/labels?api-version=6.0`,body:JSON.stringify(o),headers:{...y(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(s,e={}){let{pullRequest:t,label:n}=s;if(!t.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${w(this.config,e)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/labels/${encodeURIComponent(n.name)}?api-version=6.0`,headers:{...y(this.config,e)}})}async setPullRequestLabels(s,e={}){let{pullRequest:t,labels:n}=s;if(!t.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=t.labels;if(!o)throw new Error('Azure DevOps requires "labels" for this function.');for(let i of n)o.find(a=>a.id===i.id)||await this.addPullRequestLabel({pullRequest:t,label:i},e);for(let i of o)n.find(a=>i.id===a.id)||await this.removePullRequestLabel({pullRequest:t,label:i},e)}async setPullRequestAsDraft(s,e={}){let{pullRequest:t,isDraft:n}=s,o={isDraft:n};if(!(await this.updatePullRequest(t,JSON.stringify(o),e)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(s,e={}){let{pullRequest:t,reviewer:n,isRequired:o}=s,i={id:n.id,isRequired:o};if(!(await this.config.request({method:"PUT",url:`${w(this.config,e)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/reviewers/${n.id}?api-version=6.0`,body:JSON.stringify(i),headers:{...y(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(s,e={}){let{pullRequest:t,reviewer:n}=s;await this.config.request({method:"DELETE",url:`${w(this.config,e)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/reviewers/${n.id}?api-version=6.0`,headers:{...y(this.config,e),Accept:"application/json"}})}async setPullRequestReviewers(s,e={}){let{pullRequest:t,reviewers:n}=s;for(let o of n)t.assignees.find(i=>i.id===o.id)||await this.addPullRequestReviewer({pullRequest:t,reviewer:o,isRequired:!0},e);for(let o of t.assignees)n.find(i=>o.id===i.id)||await this.removePullRequestReviewer({pullRequest:t,reviewer:o},e)}async getIssuesForAzureProject(s,e={}){let{page:t,assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,statusByWorkItemIdByStatusId:u}=s||{},l=t||1,p=200,d=["[Microsoft.VSTS.Common.ClosedDate] = ''","[System.TeamProject] = @project","[Microsoft.VSTS.Common.ResolvedDate] = ''"];o&&d.push(`[System.CreatedBy] = '${o.replace("'","''")}'`),n&&n[0]&&d.push(`[System.AssignedTo] = '${n[0].replace("'","''")}'`),i&&d.push("[System.Id] IN (@recentMentions)"),a&&a.forEach(I=>d.push(`[System.Tags] Contains '${I}'`));let c=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${d.join(" AND ")} order by [System.CreatedDate] desc`,g=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:c}),method:"POST",headers:{...y(this.config,e),"Content-Type":"application/json"}}),m=g.body.workItems.slice((l-1)*p,p*l).map(I=>I.id);if(m.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let b=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(s.namespace)}/${encodeURIComponent(s.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:m,$expand:"Links"}),method:"POST",headers:{...y(this.config,e),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:g.body.workItems.length>p*l,nextPage:l+1},data:b.body.value.map(I=>Wr(s.namespace,s.project,I,u||{}))}}async getPermissionsForRepos(s,e={}){let{namespace:t,repos:n}=s,o={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},i=p=>{let d="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",c=`repoV2/${p.projectId}/${p.id}`;return Object.keys(o).map(g=>({securityNamespaceId:d,token:c,permissions:g}))},a={alwaysAllowAdministrators:!1,evaluations:n.flatMap(i)};return{data:(await this.config.request({method:"POST",url:`${w(this.config,e)}/${encodeURIComponent(t)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(a),headers:{...y(this.config,e),"Content-Type":"application/json"}})).body.evaluations.reduce((p,d)=>{let[,c,g]=d.token.split("/"),m=`${c}/${g}`,b=o[d.permissions];for(let I of b)p[m]===void 0&&(p[m]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),d.value===!1&&(p[m][I]=!1);return p},{})}}async decorateReposWithPermissions(s,e={}){let{namespace:t,repos:n}=s,o=await this.getPermissionsForRepos({namespace:t,repos:n},e);return{data:n.map(i=>({...i,permissions:o.data[`${i.projectId}/${i.id}`]}))}}async updateIssue(s,e,t={}){return await this.config.request({method:"PATCH",url:`${w(this.config,t)}/${encodeURIComponent(s.project.namespace)}/${encodeURIComponent(s.project.name)}/_apis/wit/workitems/${s.id}?api-version=6.0`,body:JSON.stringify(e),headers:{...y(this.config,t),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(s,e={}){let{issue:t,status:n}=s,o=[{op:"add",path:"/fields/System.State",value:n.name}];if(!(await this.updateIssue(t,o,e)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(s,e={}){let{issue:t,assignee:n}=s,o=[{op:"add",path:"/fields/System.AssignedTo",value:n?.name??""}];if(!(await this.updateIssue(t,o,e)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(s,e={}){let{issue:t,labels:n}=s,i=[{op:"replace",path:"/fields/System.Tags",value:n.map(u=>u.name).join(";")}];if(!(await this.updateIssue(t,i,e)).body.fields?.["System.Tags"])throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(s,e={}){if(!s.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:t,project:n}=s;return{data:(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t)}/${encodeURIComponent(n||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...y(this.config,e)}})).body.value}}async getLabelsForProject(s,e={}){let{namespace:t,project:n}=s;return{data:(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t)}/${encodeURIComponent(n||"")}/_apis/wit/tags?api-version=6.0`,headers:{...y(this.config,e)}})).body.value.map(i=>({color:null,description:null,id:i.id,name:i.name,url:i.url}))}}async getPullRequestForRepo(s,e={}){let{repo:t,number:n}=s;if(!t.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=await this.config.request({url:`${this.getRepoApiUrl(t.namespace,t.project,t.name,e)}/pullrequests/${n}?api-version=7.1`,headers:y(this.config,e)});return{data:le(t.namespace,o.body)}}async getMergeBase(s,e={}){if(!s.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let t=await this.config.request({url:`${this.getRepoApiUrl(s.repo.namespace,s.repo.project,s.repo.name,e)}/commits/${encodeURIComponent(s.base)}/mergebases?otherCommitId=${encodeURIComponent(s.head)}&api-version=7.1`,headers:y(this.config,e)});if(!t.body.value?.length)throw new Error("No merge base found between the specified commits.");return{data:t.body.value[0].commitId}}async getFileContents(s,e={}){if(!s.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let t=await this.config.request({url:`${this.getRepoApiUrl(s.repo.namespace,s.repo.project,s.repo.name,e)}/items?path=${encodeURIComponent(s.path)}&versionDescriptor[version]=${encodeURIComponent(s.ref)}&versionDescriptor[versionType]=commit&api-version=7.1`,headers:{...y(this.config,e),Accept:"application/octet-stream"}});return{data:new Blob([t.body])}}async getPullRequestDiff(s,e={}){if(!s.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let t=this.getRepoApiUrl(s.repo.namespace,s.repo.project,s.repo.name,e),n=y(this.config,e),o={...n,Accept:"application/octet-stream"},[i,a]=await Promise.all([this.config.request({url:`${t}/pullrequests/${s.pullRequestId}?api-version=7.1`,headers:n}),this.config.request({url:`${t}/pullrequests/${s.pullRequestId}/iterations?api-version=7.1`,headers:n})]),u=i.body.lastMergeTargetCommit.commitId,l=i.body.lastMergeSourceCommit.commitId,p=a.body.value;if(p.length===0)return"";let d=p[p.length-1],g=(await this.config.request({url:`${t}/pullrequests/${s.pullRequestId}/iterations/${d.id}/changes?api-version=7.1`,headers:n})).body.changeEntries;if(g.length===0)return"";let m=5,b=[],I=new TextDecoder,L=q=>q instanceof ArrayBuffer?I.decode(q):typeof q=="string"?q:"",A=async(q,_)=>{try{let He=await this.config.request({url:`${t}/items?path=${encodeURIComponent(q)}&versionDescriptor[version]=${encodeURIComponent(_)}&versionDescriptor[versionType]=commit&includeContent=true&api-version=7.1`,headers:o});return L(He.body)}catch{return""}},me=1,X=8,S=16;for(let q=0;q<g.length;q+=m){let _=g.slice(q,q+m),He=await Promise.all(_.map(async Z=>{let Lt=Z.item.path,Dr=(Z.changeType&me)!==0,$r=(Z.changeType&X)!==0,Dt=(Z.changeType&S)!==0&&Z.item.originalPath?Z.item.originalPath:Lt,$t=Lt,[Ur,Ar]=await Promise.all([Dr?Promise.resolve(""):A(Dt,u),$r?Promise.resolve(""):A($t,l)]);return(0,Nt.createTwoFilesPatch)(`a${Dt}`,`b${$t}`,Ur,Ar)}));b.push(...He)}return b.join(`
|
|
2
|
+
`)}};var E=(r,s={})=>R(s.token||r.token,s.isPAT||r.isPAT);var C="https://api.bitbucket.org/2.0",Jr={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},Ie={owner:4,admin:3,contributor:2,member:1},be=r=>({id:r.uuid,name:r.display_name||r.nickname,username:r.nickname||r.display_name,email:null,avatarUrl:r.links.avatar.href,url:r.links.html.href}),_t=r=>{let s=r.links.clone,e=s?.find(n=>n.name==="ssh"),t=s?.find(n=>n.name==="https");return e&&t?{cloneUrlHTTPS:t.href,cloneUrlSSH:e.href}:null},et=r=>({id:r.uuid,namespace:r.workspace.slug,name:r.slug,webUrl:r.links.html.href,httpsUrl:r.links.clone.find(s=>s.name==="https")?.href??null,sshUrl:r.links.clone.find(s=>s.name==="ssh")?.href??null,defaultBranch:{name:r.mainbranch.name},permissions:null}),tt=r=>{let s=r.id,e=r.participants?.map(t=>{let n="REVIEW_REQUESTED";return t.approved?n="APPROVED":t.state==="changes_requested"?n="CHANGES_REQUESTED":t.participated_on!==null&&(n="COMMENTED"),{reviewer:be(t.user),state:n}})??[];return{id:s.toString(),title:r.title,description:r.description,number:s,state:Jr[r.state],isDraft:!1,commentCount:r.comment_count,upvoteCount:null,author:be(r.author),createdDate:new Date(r.created_on),updatedDate:new Date(r.updated_on),closedDate:null,mergedDate:null,repository:{id:r.destination.repository.uuid,name:r.destination.repository.name,owner:{login:r.destination.repository.full_name.split("/")[0]},remoteInfo:_t(r.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:r.destination.branch.name,oid:r.destination.commit.hash},headRef:{name:r.source.branch.name,oid:r.source.commit.hash},url:r.links.html.href,assignees:null,reviews:e,reviewDecision:O(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:{id:r.source.repository.uuid,name:r.source.repository.name,owner:{login:r.source.repository.full_name.split("/")[0]},remoteInfo:_t(r.source.repository)},mergeableState:"MERGEABLE",permissions:null}},Vr=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}}},Kr=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}}},te=class extends G{async refreshToken(s){return{data:(await this.config.request({url:"https://bitbucket.org/site/oauth2/access_token",method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Basic ${s.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${s.refreshToken}`})).body}}async getCurrentUser(s={},e={}){let t=await this.config.request({url:`${C}/user`,headers:E(this.config,e)});return{data:be(t.body)}}async getUserForCommit(s,e={}){let n=(await this.config.request({url:`${C}/repositories/${s.repo.namespace}/${s.repo.name}/commit/${s.oid}`,headers:E(this.config,e)})).body.author,o=n.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:n.user?.links.avatar.href||null}}}async getRepo(s,e={}){let t=await this.config.request({url:`${C}/repositories/${s.namespace}/${s.name}`,headers:E(this.config,e)});return{data:et(t.body)}}async getRepos(s,e={}){let t=[],n=[];return await Promise.all(s.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:t,errors:n}}async getReposForWorkspace(s,e={}){let t=new URL(`${C}/repositories/${encodeURIComponent(s.workspace)}`);t.searchParams.set("page",s.page?.toString()||"1"),t.searchParams.set("pagelen",v.toString()),s.minimumRole&&t.searchParams.set("role",s.minimumRole);let n=await this.config.request({url:t.toString(),headers:E(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(et)}}async getAllReposForWorkspace(s,e={}){let t=[],n=1;for(;n!==null;){let o=await this.getReposForWorkspace({workspace:s.workspace,minimumRole:s.minimumRole,page:n},e);t.push(...o.data),n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}return t}async getAllReposForWorkspaceWithPermissions(s,e={}){let t=new Map,n=[],o=Ie[s.minimumRole||"member"];o<=Ie.admin&&n.push("admin"),o<=Ie.contributor&&n.push("contributor"),o<=Ie.member&&n.push("member");let i=[];for(let a of n){i=await this.getAllReposForWorkspace({workspace:s.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:Kr(u)}})}}async getReposForCurrentUser(s,e={}){let t=new URL(`${C}/repositories`);t.searchParams.set("role","member"),t.searchParams.set("pagelen",v.toString()),s.cursor&&t.searchParams.set("after",s.cursor);let n=await this.config.request({url:t.toString(),headers:E(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(et)}}async getBranches(s,e={}){let t=new URL(`${C}/repositories/${s.repo.namespace}/${s.repo.name}/refs/branches`);t.searchParams.set("page",s.page?.toString()||"1"),t.searchParams.set("pagelen",v.toString());let n=await this.config.request({url:t.toString(),headers:E(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>{let a=new Date(i.target.date);return{name:i.name,commit:{oid:i.target.hash,authoredDate:a,committedDate:a}}})}}async getTags(s,e={}){let t=new URL(`${C}/repositories/${s.repo.namespace}/${s.repo.name}/refs/tags`);t.searchParams.set("pagelen",v.toString()),s.cursor&&t.searchParams.set("page",s.cursor);let n=await this.config.request({url:t.toString(),headers:E(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(a=>{let u=new Date(a.target.date);return{name:a.name,commit:{oid:a.target.hash,authoredDate:u,committedDate:u}}})}}async getWorkspacesForCurrentUser(s={},e={}){let t=new URL(`${C}/user/workspaces`);t.searchParams.set("page",s?.page?.toString()||"1"),t.searchParams.set("pagelen","50"),s?.administrator!==void 0&&t.searchParams.set("administrator",s.administrator.toString());let n=await this.config.request({url:t.toString(),headers:E(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug}))}}async getWorkspacesForUser(s,e={}){let t=new URL(`${C}/user/permissions/workspaces`);t.searchParams.set("page",s.page?.toString()||"1"),t.searchParams.set("pagelen","50");let n=await this.config.request({url:t.toString(),headers:E(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(s,e={}){let t=new URL(`${C}/workspaces/${s.workspaceSlug}/pullrequests/${s.userId}`);if(t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",s.page?.toString()||"1"),t.searchParams.set("pagelen","50"),s.repos&&s.repos.length>0){let i=`state = "open" AND (${s.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`;t.searchParams.set("q",i)}let n=await this.config.request({url:t.toString(),headers:E(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(tt)}}async getPullRequestsForRepoBase(s,e={}){let t=new URL(`${C}/repositories/${encodeURI(s.repo.namespace)}/${encodeURI(s.repo.name)}/pullrequests?state=OPEN`),n=[];s.reviewerId&&n.push(`reviewers.uuid="${s.reviewerId}"`),s.authorLogin&&n.push(`author.uuid="${s.authorLogin}"`);let o='state="OPEN"';return n.length&&(o+=` AND (${n.join(s.useOrFilter?" OR ":" AND ")})`),t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",s.page?.toString()||"1"),t.searchParams.set("pagelen","50"),t.searchParams.set("q",o),await this.config.request({url:t.toString(),headers:E(this.config,e)})}async getPullRequestsForRepo(s,e={}){let t=[],n=await this.getPullRequestsForRepoBase(s,e);n.body.values.forEach(i=>{t.push(tt(i))});let o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:t}}async getPullRequestsForRepos(s,e={}){let t=[];return await Promise.all(s.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...s},e)).body.values.forEach(i=>{t.push(tt(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getAccountsForWorkspace(s,e={}){let t=new URL(`${C}/workspaces/${encodeURI(s.workspace)}/members`);t.searchParams.set("page",s.page?.toString()||"1"),t.searchParams.set("pagelen","100");let n=await this.config.request({url:t.toString(),headers:E(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>be(i.user))}}async getReposPermissionsForCurrentUser(s,e={}){let t=new URL(`${C}/user/permissions/repositories`);t.searchParams.set("page",s.page?.toString()||"1"),t.searchParams.set("pagelen","100");let n=await this.config.request({url:t.toString(),headers:E(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.reduce((i,a)=>({...i,[a.repository.uuid]:Vr(a.permission)}),{})}}async decorateReposWithPermissions(s,e={}){let t={},n=1;do{let o=await this.getReposPermissionsForCurrentUser({page:n},e);t={...o.data,...t},n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(n!==null);return{data:s.repos.map(o=>({...o,permissions:t[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(s,e={}){let{pullRequest:t}=s;if(!(await this.config.request({method:"POST",url:`${C}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/decline`,headers:E(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(s,e={}){let{pullRequest:t,mergeStrategy:n}=s,o;switch(n){case"MERGE_COMMIT":{o="merge_commit";break}case"FAST_FORWARD":{o="fast_forward";break}case"SQUASH":{o="squash";break}}let i={merge_strategy:o,type:"pullrequest"};if(!(await this.config.request({method:"POST",url:`${C}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/merge`,body:JSON.stringify(i),headers:{...E(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(s,e={}){let{pullRequest:t,reviewers:n}=s,o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket reviewer requires "username" for this function.');return{username:a.username}})};if(!(await this.config.request({method:"PUT",url:`${C}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}`,body:JSON.stringify(o),headers:{...E(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var Ft=r=>r?r.find(s=>s.permission==="USER_ADMIN"||s.permission==="PROJECT_ADMIN"||s.permission==="ADMIN"||s.permission==="SYS_ADMIN"||s.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:r.find(s=>s.permission==="REPO_WRITE"||s.permission==="REPO_CREATE"||s.permission==="PROJECT_CREATE"||s.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var pe=r=>{let s=r.links.self[0].href;return{name:r.displayName,email:r.emailAddress,avatarUrl:r.avatarUrl??(s&&`${s}/avatar.png`),id:r.id.toString(),username:r.name,url:s}},ye=r=>{let s={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},t=r.reviewers.map(u=>({reviewer:pe(u.user),state:e[u.status]})),n=r.toRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,o=r.toRef.repository.links.clone.find(u=>u.name==="https")?.href??null;o||(o=r.toRef.repository.links.clone.find(u=>u.name==="http")?.href??null);let i=r.fromRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,a=r.fromRef.repository.links.clone.find(u=>u.name==="https")?.href??null;return a||(a=r.fromRef.repository.links.clone.find(u=>u.name==="http")?.href??null),{id:r.id.toString(),number:r.id,title:r.title,description:r.description,url:r.links.self[0].href,state:s[r.state],isDraft:!1,createdDate:new Date(r.createdDate),updatedDate:new Date(r.updatedDate),closedDate:r.closedDate?new Date(r.closedDate):null,mergedDate:r.state=="MERGED"&&r.closedDate?new Date(r.closedDate):null,baseRef:{name:r.toRef.displayId,oid:r.toRef.latestCommit},headRef:{name:r.fromRef.displayId,oid:r.fromRef.latestCommit},commentCount:r.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:pe(r.author.user),assignees:null,reviews:t,reviewDecision:O(t),repository:{id:r.toRef.repository.id.toString(),name:r.toRef.repository.name,owner:{login:r.toRef.repository.project.key},remoteInfo:o&&n?{cloneUrlHTTPS:o,cloneUrlSSH:n}:null},headRepository:{id:r.fromRef.repository.id.toString(),name:r.fromRef.repository.name,owner:{login:r.fromRef.repository.project.key},remoteInfo:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:r.version}},Qt=r=>({id:r.id.toString(),namespace:r.project.key,name:r.slug,webUrl:r.links.self[0]?.href??null,httpsUrl:r.links.clone.find(s=>s.name==="https"||s.name==="http")?.href??null,sshUrl:r.links.clone.find(s=>s.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),re=class extends ${getBaseUrl(s){let e=s.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(s){return R(s.token||this.config.token)}async getCurrentUser(s={},e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":n,"x-ausername":o}}=t,i=n?parseInt(n,10):null,a=decodeURIComponent(o),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:p,id:d,name:c,slug:g})=>i?i===d:a===c||a===p||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:pe(l)}}async getUserForCommit(s,e){let{repo:t,oid:n}=s,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}/commits/${n}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:pe(o.body.author)}}async getRepo(s,e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${s.namespace}/repos/${s.name}`,headers:this.getRequestHeaders(e)});return{data:Qt(t.body)}}async getRepos(s,e={}){let t=[],n=[];return await Promise.all(s.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:t,errors:n}}async getReposForCurrentUser(s,e={}){let t=s.page??0,n=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${t}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!n.body.isLastPage,nextPage:n.body.nextPageStart},data:n.body.values.map(Qt)}}async getRepoPermissionsForUsername(s,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${s.repo.namespace}/repos/${s.repo.name}/permissions/search?filterText=${s.username}`);try{let n=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)});return{data:Ft(n.body.values)}}catch(n){if(n.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw n}}async decorateReposWithPermissions(s,e={}){return await Promise.all(s.repos.map(async n=>{let o=await this.getRepoPermissionsForUsername({repo:n,username:s.username},e);return{...n,permissions:o.data}}))}async getPullRequestsForRepoBase(s,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(s.repo.namespace)}/repos/${encodeURI(s.repo.name)}/pull-requests?state=OPEN`);return t.searchParams.set("start",s.page?.toString()||"0"),t.searchParams.set("limit","50"),await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(s,e={}){let t=[],n=await this.getPullRequestsForRepoBase(s,e);n.body.values.forEach(i=>{if(s.authorLogin&&i.author.user.name!==s.authorLogin)return null;t.push(ye(i))});let o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:t}}async getPullRequestsForRepos(s,e={}){let t=[];return await Promise.all(s.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...s},e)).body.values.forEach(i=>{if(s.authorLogin&&i.author.user.name!==s.authorLogin)return null;t.push(ye(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getPullRequestsForCurrentUser(s,e={}){let t=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);t.searchParams.set("state","OPEN"),t.searchParams.set("start",s.page?.toString()||"0"),t.searchParams.set("limit","50");let n=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(ye)}}async closePullRequest(s,e={}){let{pullRequest:t}=s;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/decline`,body:JSON.stringify({version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(s,e={}){let{pullRequest:t,mergeStrategyId:n}=s;if(s.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/merge`,body:JSON.stringify({strategyId:n,version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(s={}){let e=await this.config.request({url:`${this.getBaseUrl(s)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(s),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(s,e={}){let{pullRequest:t,reviewers:n}=s;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:a.username}}}),version:t.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}async getAccountsForProject(s,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(s.project)}/permissions/users`);t.searchParams.set("start",s.page?.toString()||"0"),t.searchParams.set("limit","50");let n=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(i=>pe(i.user))}}};var rr=require("js-base64");var Pe=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(Pe||{});var h=class extends Error{constructor(e,t){let n=t?.map(i=>`'${i.message}'`).join(", "),o=n?`${e}: ${n}`:e;super(o);this.graphQLErrors=t??[]}};var Xr={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]},jt=15,Bt=100,de={__typename:"User",id:"U_kgDNJ5k",databaseId:10137,name:"Deleted user",login:"ghost",email:"",avatarUrl:"https://avatars.githubusercontent.com/u/10137?v=4",url:"https://github.com/ghost"},D=r=>!!r,x=(r,s)=>{let e=Xr[s];for(let t=0;t<3;t++){if(r[t]>e[t])return!0;if(r[t]<e[t])return!1}return!0},Se="https://api.github.com",Zr=`${Se}/graphql`,ve=`
|
|
2
3
|
description
|
|
3
4
|
dueOn
|
|
4
5
|
id
|
|
@@ -6,7 +7,7 @@ number
|
|
|
6
7
|
state
|
|
7
8
|
title
|
|
8
9
|
url
|
|
9
|
-
`,
|
|
10
|
+
`,Yr=`
|
|
10
11
|
... on CheckRun {
|
|
11
12
|
completedAt
|
|
12
13
|
conclusion
|
|
@@ -15,63 +16,63 @@ url
|
|
|
15
16
|
permalink
|
|
16
17
|
startedAt
|
|
17
18
|
}
|
|
18
|
-
`,
|
|
19
|
+
`,we=/\/api\/v\d+$/,qe=`
|
|
19
20
|
color
|
|
20
21
|
description
|
|
21
22
|
id
|
|
22
23
|
name
|
|
23
|
-
`,
|
|
24
|
+
`,Mt=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.")},es=(r,s)=>{let e=s.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Mt(e),we.test(e)&&(e=e.replace(we,"")),`${e}/api/graphql`):Zr},K=(r,s)=>{let e=s.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Mt(e),we.test(e)&&(e=e.replace(we,"")),`${e}/api/v3`):Se},f=(r,s,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:es(r,e),method:"POST",headers:t,body:JSON.stringify(s)})},ts={user:!0,"user:email":!0,"read:user":!0},F=r=>r.some(s=>ts[s]),U=(r=!1,s=!1,e)=>`
|
|
24
25
|
__typename
|
|
25
|
-
${
|
|
26
|
-
${
|
|
27
|
-
${
|
|
28
|
-
${
|
|
29
|
-
${s?
|
|
30
|
-
${
|
|
31
|
-
${
|
|
32
|
-
`,
|
|
26
|
+
${z(e,["graphQLId"],"id")}
|
|
27
|
+
${z(e,["id"],"databaseId")}
|
|
28
|
+
${z(e,["name"],"name")}
|
|
29
|
+
${z(e,["name","username"],"login")}
|
|
30
|
+
${s?z(e,["email"],"email"):""}
|
|
31
|
+
${z(e,["avatarUrl"],`avatarUrl${r?"(size: $avatarSize)":""}`)}
|
|
32
|
+
${z(e,["url"],"url")}
|
|
33
|
+
`,rs=(r=!1)=>`
|
|
33
34
|
latestReviews(first: 100) {
|
|
34
35
|
nodes {
|
|
35
36
|
author {
|
|
36
37
|
... on User {
|
|
37
|
-
${
|
|
38
|
+
${U(!1,r)}
|
|
38
39
|
}
|
|
39
40
|
... on EnterpriseUserAccount {
|
|
40
|
-
${
|
|
41
|
+
${rt(!1)}
|
|
41
42
|
}
|
|
42
43
|
}
|
|
43
44
|
state
|
|
44
45
|
}
|
|
45
46
|
}
|
|
46
|
-
`,
|
|
47
|
+
`,zt=(r=!1)=>`
|
|
47
48
|
__typename
|
|
48
49
|
id
|
|
49
50
|
databaseId
|
|
50
51
|
login
|
|
51
52
|
avatarUrl${r?"(size: $avatarSize)":""}
|
|
52
53
|
url
|
|
53
|
-
`,
|
|
54
|
+
`,rt=(r=!1)=>`
|
|
54
55
|
__typename
|
|
55
56
|
id
|
|
56
57
|
login
|
|
57
58
|
avatarUrl${r?"(size: $avatarSize)":""}
|
|
58
59
|
url
|
|
59
|
-
`,
|
|
60
|
+
`,Ee=(r,s=!1,e)=>`
|
|
60
61
|
id
|
|
61
|
-
${!e||
|
|
62
|
+
${!e||x(e,"PR_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
62
63
|
number
|
|
63
64
|
title
|
|
64
65
|
body
|
|
65
66
|
state
|
|
66
67
|
author {
|
|
67
68
|
... on User {
|
|
68
|
-
${
|
|
69
|
+
${U(!1,s)}
|
|
69
70
|
}
|
|
70
71
|
... on Bot {
|
|
71
|
-
${
|
|
72
|
+
${zt(!1)}
|
|
72
73
|
}
|
|
73
74
|
... on EnterpriseUserAccount {
|
|
74
|
-
${
|
|
75
|
+
${rt(!1)}
|
|
75
76
|
}
|
|
76
77
|
}
|
|
77
78
|
commits(last: 1) {
|
|
@@ -84,7 +85,7 @@ commits(last: 1) {
|
|
|
84
85
|
contexts(first: 100) {
|
|
85
86
|
totalCount
|
|
86
87
|
nodes {
|
|
87
|
-
${!e||
|
|
88
|
+
${!e||x(e,"CHECK_RUN")?Yr:""}
|
|
88
89
|
... on StatusContext {
|
|
89
90
|
context
|
|
90
91
|
createdAt
|
|
@@ -146,47 +147,47 @@ closedAt
|
|
|
146
147
|
mergedAt
|
|
147
148
|
assignees(first: 100) {
|
|
148
149
|
nodes {
|
|
149
|
-
${
|
|
150
|
+
${U(!1,s)}
|
|
150
151
|
}
|
|
151
152
|
}
|
|
152
153
|
reviewRequests(first: 100) {
|
|
153
154
|
nodes {
|
|
154
|
-
${!e||
|
|
155
|
+
${!e||x(e,"AS_CODE_OWNER")?"asCodeOwner":""}
|
|
155
156
|
requestedReviewer {
|
|
156
157
|
... on User {
|
|
157
|
-
${
|
|
158
|
+
${U(!1,s)}
|
|
158
159
|
}
|
|
159
160
|
}
|
|
160
161
|
}
|
|
161
162
|
}
|
|
162
|
-
${!e||
|
|
163
|
+
${!e||x(e,"LATEST_REVIEWS")?rs(s):""}
|
|
163
164
|
additions
|
|
164
165
|
deletions
|
|
165
166
|
changedFiles
|
|
166
167
|
mergeable
|
|
167
168
|
mergeStateStatus
|
|
168
169
|
milestone {
|
|
169
|
-
${
|
|
170
|
+
${ve}
|
|
170
171
|
}
|
|
171
172
|
labels(first: 100) {
|
|
172
173
|
nodes {
|
|
173
|
-
${
|
|
174
|
+
${qe}
|
|
174
175
|
}
|
|
175
176
|
}
|
|
176
|
-
${!e||
|
|
177
|
-
`,
|
|
177
|
+
${!e||x(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
|
|
178
|
+
`,ss=(r=!1,s)=>`
|
|
178
179
|
id
|
|
179
|
-
${!s||
|
|
180
|
+
${!s||x(s,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
180
181
|
title
|
|
181
182
|
author {
|
|
182
183
|
... on User {
|
|
183
|
-
${
|
|
184
|
+
${U(!1,r)}
|
|
184
185
|
}
|
|
185
186
|
... on Bot {
|
|
186
|
-
${
|
|
187
|
+
${zt(!1)}
|
|
187
188
|
}
|
|
188
189
|
... on EnterpriseUserAccount {
|
|
189
|
-
${
|
|
190
|
+
${rt(!1)}
|
|
190
191
|
}
|
|
191
192
|
}
|
|
192
193
|
closedAt
|
|
@@ -210,19 +211,19 @@ comments {
|
|
|
210
211
|
}
|
|
211
212
|
assignees(first: 100) {
|
|
212
213
|
nodes {
|
|
213
|
-
${
|
|
214
|
+
${U(!1,r)}
|
|
214
215
|
}
|
|
215
216
|
}
|
|
216
217
|
state
|
|
217
218
|
milestone {
|
|
218
|
-
${
|
|
219
|
+
${ve}
|
|
219
220
|
}
|
|
220
221
|
labels(first: 100) {
|
|
221
222
|
nodes {
|
|
222
|
-
${
|
|
223
|
+
${qe}
|
|
223
224
|
}
|
|
224
225
|
}
|
|
225
|
-
`,
|
|
226
|
+
`,ns={"-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"},os=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),st=r=>{let s=[];return(r.match(os)??[]).forEach(t=>{if(t.includes(":")&&t!="is:closed"){let n=t.split(":")[0];ns[n]&&s.push(t)}}),s},nt=(r,s,e,t)=>{let n=r==="issue";return{query:`
|
|
226
227
|
query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
227
228
|
search(type:ISSUE query:$query first: ${t.maxPageSize} after:$after) {
|
|
228
229
|
pageInfo {
|
|
@@ -231,18 +232,18 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
231
232
|
}
|
|
232
233
|
nodes {
|
|
233
234
|
... on ${n?"Issue":"PullRequest"} {
|
|
234
|
-
${n?
|
|
235
|
+
${n?ss(t.supportsEmail,t.enterpriseVersion??null):Ee(t.supportsDrafts??!1,t.supportsEmail,t.enterpriseVersion??null)}
|
|
235
236
|
}
|
|
236
237
|
}
|
|
237
238
|
}
|
|
238
|
-
}`,variables:{query:`is:${r} is:open ${t.includeFromArchivedRepos?"":"archived:false"} ${s}`,after:e}}},
|
|
239
|
+
}`,variables:{query:`is:${r} is:open ${t.includeFromArchivedRepos?"":"archived:false"} ${s}`,after:e}}},is="Field 'isDraft' doesn't exist on type 'PullRequest'",Ce=(r=[])=>r.some(s=>s?.message===is),as=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,us=`
|
|
239
240
|
\
|
|
240
|
-
+`,
|
|
241
|
+
+`,Ht=(r,s,e,t)=>{let n=as.exec(r);if(!n||!n[0]||!n[1])return[];let o=parseInt(n[1],10),i=parseInt(n[2],10),a=r.replace(us,`
|
|
241
242
|
+`).split(`
|
|
242
243
|
`).slice(1),u=o-1,l=i-1,p=a.map(g=>{let m,b;switch(g[0]){case"-":{m="DELETED",u+=1,b=`${g.slice(1)}
|
|
243
244
|
`;break}case"+":{m="ADDED",l+=1,b=`${g.slice(1)}
|
|
244
245
|
`;break}default:m="UNMODIFIED",l+=1,u+=1,b=`${g}
|
|
245
|
-
`}return{line:b,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),d=e,c=s;if(d!==null&&c!==null&&t!==null&&d<c){let g=0,m=p.length,b=t==="LEFT"?"oldLineNumber":"newLineNumber";for(let I=0;I<p.length;I++){let
|
|
246
|
+
`}return{line:b,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),d=e,c=s;if(d!==null&&c!==null&&t!==null&&d<c){let g=0,m=p.length,b=t==="LEFT"?"oldLineNumber":"newLineNumber";for(let I=0;I<p.length;I++){let A=p[I][b];A===d?g=I:A===c&&(m=I)}p=p.slice(g,m+1)}return p},Wt=r=>{let s=r.author;return s||(s=de),{author:{id:"databaseId"in s?s.databaseId.toString():s.id,graphQLId:s.id,name:("name"in s?s.name:s.login)??s.login,username:s.login,email:("email"in s?s.email:null)??null,avatarUrl:s.avatarUrl,url:s.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 Jt=`mutation DeleteIssueComment(
|
|
246
247
|
$issueCommentId: ID!
|
|
247
248
|
) {
|
|
248
249
|
deleteIssueComment(input: {
|
|
@@ -250,7 +251,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
250
251
|
}) {
|
|
251
252
|
clientMutationId
|
|
252
253
|
}
|
|
253
|
-
}`,
|
|
254
|
+
}`,Vt=`mutation DeletePullRequestReviewComment(
|
|
254
255
|
$pullRequestReviewCommentId: ID!
|
|
255
256
|
) {
|
|
256
257
|
deletePullRequestReviewComment(input: {
|
|
@@ -260,7 +261,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
260
261
|
id
|
|
261
262
|
}
|
|
262
263
|
}
|
|
263
|
-
}`,
|
|
264
|
+
}`,Kt=`mutation UpdateIssueComment(
|
|
264
265
|
$issueCommentId: ID!,
|
|
265
266
|
$body: String!
|
|
266
267
|
) {
|
|
@@ -273,7 +274,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
273
274
|
body
|
|
274
275
|
}
|
|
275
276
|
}
|
|
276
|
-
}`,
|
|
277
|
+
}`,Xt=`mutation ResolveReviewThread(
|
|
277
278
|
$pullRequestReviewThreadId: ID!
|
|
278
279
|
) {
|
|
279
280
|
resolveReviewThread(input: {
|
|
@@ -284,7 +285,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
284
285
|
isResolved
|
|
285
286
|
}
|
|
286
287
|
}
|
|
287
|
-
}`,
|
|
288
|
+
}`,Zt=`mutation UnresolveReviewThread(
|
|
288
289
|
$pullRequestReviewThreadId: ID!
|
|
289
290
|
) {
|
|
290
291
|
unresolveReviewThread(input: {
|
|
@@ -295,7 +296,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
295
296
|
isResolved
|
|
296
297
|
}
|
|
297
298
|
}
|
|
298
|
-
}`,
|
|
299
|
+
}`,Yt=`mutation UpdatePullRequestReviewComment(
|
|
299
300
|
$pullRequestReviewCommentId: ID!,
|
|
300
301
|
$body: String!
|
|
301
302
|
) {
|
|
@@ -308,7 +309,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
308
309
|
body
|
|
309
310
|
}
|
|
310
311
|
}
|
|
311
|
-
}`;var
|
|
312
|
+
}`;var er=r=>`
|
|
312
313
|
query GetPullRequestComments(
|
|
313
314
|
$namespace: String!
|
|
314
315
|
$name: String!
|
|
@@ -354,7 +355,7 @@ query GetPullRequestComments(
|
|
|
354
355
|
}
|
|
355
356
|
}
|
|
356
357
|
}
|
|
357
|
-
`;var
|
|
358
|
+
`;var ot=`
|
|
358
359
|
id
|
|
359
360
|
databaseId
|
|
360
361
|
owner {
|
|
@@ -367,18 +368,18 @@ defaultBranchRef {
|
|
|
367
368
|
name
|
|
368
369
|
}
|
|
369
370
|
viewerPermission
|
|
370
|
-
`,
|
|
371
|
+
`,ls={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},ps={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},ds={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},cs={OPEN:"OPEN",CLOSED:"CLOSED"},gs=["ADMIN","MAINTAIN","TRIAGE","WRITE"],ut=r=>({color:`#${r.color}`,description:r.description,graphQLId:r.id,id:null,name:r.name}),ms=r=>({canCreateWebhook:r==="ADMIN",canPush:r==="ADMIN"||r==="MAINTAIN"||r==="WRITE",isAdmin:r==="ADMIN"}),it=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:ms(r.viewerPermission)}),hs=r=>({canCreateWebhook:r.admin,canPush:r.admin||r.maintain||r.push,isAdmin:r.admin}),tr=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:hs(r.permissions)}),fs=r=>({path:r.path,isDirectory:r.type==="tree"}),Rs={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},Is={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},T=(r,s=Is)=>{let e={};return s.id&&(e.id="databaseId"in r?r.databaseId.toString():r.id),s.graphQLId&&(e.graphQLId=r.id),s.name&&(e.name=r.name??r.login),s.username&&(e.username=r.login),s.email&&(e.email=r.email??null),s.avatarUrl&&(e.avatarUrl=r.avatarUrl),s.url&&(e.url=r.url),e},bs=(r,s)=>{let e={IN_PROGRESS:"RUNNING",PENDING:"PENDING",QUEUED:"PENDING",REQUESTED:"PENDING",WAITING:"PENDING"};return r!=="COMPLETED"?e[r]:{ACTION_REQUIRED:"ACTION_REQUIRED",CANCELLED:"CANCELLED",FAILURE:"FAILED",NEUTRAL:null,SKIPPED:"SKIPPED",STALE:"FAILED",STARTUP_FAILURE:"FAILED",SUCCESS:"SUCCESS",TIMED_OUT:"ERROR"}[s]},ys=r=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[r],at=r=>{let s=null;r.author?s=r.author:s=de;let e=(r.reviewRequests?.nodes||[]).filter(D).filter(i=>!i.asCodeOwner),t=r.headRepository?.url;t&&!t.endsWith(".git")&&(t=`${t}.git`);let n=r.repository?.url;n&&!n.endsWith(".git")&&(n=`${n}.git`);let o=e.filter(i=>i.requestedReviewer&&"__typename"in i.requestedReviewer).map(i=>({reviewer:T(i.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((r.latestReviews?.nodes||[]).filter(D).map(i=>{let a=de;return i.author&&i.author.__typename&&(a=i.author),{reviewer:T(a),state:ls[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:Rs[r.state],commentCount:r.comments.totalCount,upvoteCount:r.reactions.totalCount,author:s&&s.__typename?T(s):null,createdDate:new Date(r.createdAt),isDraft:r.isDraft,repository:{id:r.repository.databaseId.toString(),graphQLId:r.repository.id,name:r.repository.name,owner:{login:r.repository.owner.login},remoteInfo:{cloneUrlHTTPS:n,cloneUrlSSH:r.repository.sshUrl}},headRepository:r.headRepository?{id:r.headRepository.databaseId.toString(),graphQLId:r.headRepository.id,name:r.headRepository.name,owner:{login:r.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:t,cloneUrlSSH:r.headRepository.sshUrl}}:null,headCommit:{buildStatuses:r.commits.nodes?.filter(D)[0]?.commit.statusCheckRollup?.contexts.nodes?.filter(D).map(i=>"context"in i?{completedAt:null,description:i.description,name:i.context,state:ys(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:bs(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(D).map(i=>T(i)):null,reviews:o,reviewDecision:O(o),additions:r.additions,deletions:r.deletions,fileCount:r.changedFiles,commitCount:r.commits.totalCount,mergeableState:ds[r.mergeStateStatus]??ps[r.mergeable],milestone:r.milestone?lt(r.milestone):null,labels:r.labels?.nodes?.filter(D).map(ut)??[],permissions:{canMerge:gs.includes(r.repository.viewerPermission),canMergeAndBypassProtections:r.viewerCanMergeAsAdmin??!1}}},Ps=r=>{let{id:s,comments:e,isOutdated:t,isResolved:n,line:o,startLine:i,diffSide:a,originalLine:u,originalStartLine:l,startDiffSide:p}=r,d=e.nodes?.[0];if(!d)return null;let{author:c,body:g,databaseId:m,fullDatabaseId:b,id:I,path:L,publishedAt:A,url:me}=d,X=o??u,S=i??l,q=a??p;return{author:c?{avatarUrl:c.avatarUrl,email:null,name:c.login}:null,body:g,createdAt:A?new Date(A):null,diffLines:Ht(d.diffHunk,X,S,q),id:b??m.toString(),isOutdated:t,isResolved:n,graphQLId:I,threadId:s,filename:L,replies:e.nodes?.filter(D).slice(1).map(ws)??[],url:me,line:X,startLine:S,side:q}},ws=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}),Ss=r=>{let s=null;return r.author?s=r.author:s=de,{id:r.fullDatabaseId!==void 0?r.fullDatabaseId:r.databaseId.toString(),graphQLId:r.id,number:r.number,title:r.title,author:s&&s.__typename?T(s):null,commentCount:r.comments.totalCount,closedDate:r.closedAt?new Date(r.closedAt):null,createdDate:new Date(r.createdAt),description:null,state:{name:cs[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(D).map(e=>T(e))??[],upvoteCount:r.reactions.totalCount,milestone:r.milestone?lt(r.milestone):null,labels:r.labels?.nodes?.filter(D).map(ut)??[]}},lt=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}),se=class extends ${constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let t=e.token||this.config.token;if(!t)return[];let n=this._scopesCache[t];if(!n){let i=(await f(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];n=i?i.split(", "):[],this._scopesCache[t]=n}return n}async getEnterpriseVersion(e){let t=e.baseUrl||this.config.baseUrl;if(!t)return null;let n=this._enterpriseVersionsCache[t];if(!n){let o=await this.config.request({url:`${K(this.config,e)}/meta`,headers:R(e.token||this.config.token)});if(!o.body.installed_version)return null;n=o.body.installed_version.split(".").slice(0,3).map(i=>parseInt(i,10)),this._enterpriseVersionsCache[t]=n}return n}getEnterpriseAvatarUrlIfNeeded(e,t,n){let o=n.baseUrl||this.config.baseUrl;return!o||o.startsWith(Se)?e:t?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(t)}`:""}async getCurrentUser(e={},t={}){if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let n=Tt(e.fields),o=await this.getScopes(t),i=await f(this.config,{query:`
|
|
371
372
|
query getCurrentUser {
|
|
372
373
|
viewer {
|
|
373
|
-
${
|
|
374
|
+
${U(!1,F(o),n)}
|
|
374
375
|
}
|
|
375
376
|
}
|
|
376
|
-
`},t),a=i.body.data?.viewer;if(!a)throw new h("Current user not found.",i.body.errors);return{data:
|
|
377
|
+
`},t),a=i.body.data?.viewer;if(!a)throw new h("Current user not found.",i.body.errors);return{data:T(a,n)}}async getAccountsForRepo(e,t={}){let n=await this.getScopes(t),{repo:{namespace:o,name:i},cursor:a}=e,u=await f(this.config,{query:`
|
|
377
378
|
query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
|
|
378
379
|
repository(owner: $owner, name: $name) {
|
|
379
380
|
assignableUsers(first: $first, after: $cursor) {
|
|
380
381
|
nodes {
|
|
381
|
-
${
|
|
382
|
+
${U(!1,F(n))}
|
|
382
383
|
}
|
|
383
384
|
pageInfo {
|
|
384
385
|
endCursor
|
|
@@ -387,7 +388,7 @@ query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first
|
|
|
387
388
|
}
|
|
388
389
|
}
|
|
389
390
|
}
|
|
390
|
-
`,variables:{owner:o,name:i,cursor:a,first:
|
|
391
|
+
`,variables:{owner:o,name:i,cursor:a,first:v}},t);if(!u.body.data)throw new h("Could not fetch accounts for repo",u.body.errors);return{pageInfo:u.body.data.repository?.assignableUsers?.pageInfo??{endCursor:null,hasNextPage:!1},data:u.body.data.repository?.assignableUsers?.nodes?.map(l=>T(l))??[]}}async getUserForCommit(e,t={}){let n=await f(this.config,{query:`
|
|
391
392
|
query getUserForCommit(
|
|
392
393
|
$owner: String!
|
|
393
394
|
$name: String!
|
|
@@ -433,23 +434,23 @@ mutation createCommitOnBranch(
|
|
|
433
434
|
}
|
|
434
435
|
}
|
|
435
436
|
}
|
|
436
|
-
`,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([p,d])=>({contents:
|
|
437
|
+
`,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([p,d])=>({contents:rr.Base64.encode(d),path:p})),deletions:o.map(p=>({path:p}))},message:{body:n.description,headline:n.summary},repositoryNameWithOwner:`${a.namespace}/${a.name}`}},t);if(!l.body.data)throw new h("Could not create commit",l.body.errors);return{data:{name:l.body.data.createCommitOnBranch.ref.name,commit:{authoredDate:new Date(l.body.data.createCommitOnBranch.commit.authoredDate),committedDate:new Date(l.body.data.createCommitOnBranch.commit.committedDate),oid:l.body.data.createCommitOnBranch.commit.oid}}}}async getAccountForEmail(e,t={}){let n=await this.getScopes(t),o=await f(this.config,{query:`
|
|
437
438
|
query getAccountForEmail($query: String! $avatarSize: Int) {
|
|
438
439
|
search(query: $query, type: USER, first: 1) {
|
|
439
440
|
nodes {
|
|
440
441
|
... on User {
|
|
441
|
-
${
|
|
442
|
+
${U(!0,F(n))}
|
|
442
443
|
}
|
|
443
444
|
}
|
|
444
445
|
}
|
|
445
446
|
}
|
|
446
|
-
`,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},t),i=o.body.data?.search?.nodes?.[0];if(!i)throw new h("Could not find user via email",o.body.errors);return{data:
|
|
447
|
+
`,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},t),i=o.body.data?.search?.nodes?.[0];if(!i)throw new h("Could not find user via email",o.body.errors);return{data:T({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)})}}async getAccountForUsername(e,t={}){let n=await this.getScopes(t),o=await f(this.config,{query:`
|
|
447
448
|
query getUserForUsername($login: String! $avatarSize: Int) {
|
|
448
449
|
user(login: $login) {
|
|
449
|
-
${
|
|
450
|
+
${U(!0,F(n))}
|
|
450
451
|
}
|
|
451
452
|
}
|
|
452
|
-
`,variables:{login:e.username,avatarSize:e.avatarSize}},t),i=o.body.data?.user;if(!i)throw new h("Could not find user via username",o.body.errors);return{data:
|
|
453
|
+
`,variables:{login:e.username,avatarSize:e.avatarSize}},t),i=o.body.data?.user;if(!i)throw new h("Could not find user via username",o.body.errors);return{data:T({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)})}}async getOrgsForCurrentUser(e={},t={}){let n=await f(this.config,{query:`
|
|
453
454
|
query getOrgsForCurrentUser($cursor: String, $first: Int!) {
|
|
454
455
|
viewer {
|
|
455
456
|
organizations(first: $first after: $cursor) {
|
|
@@ -468,7 +469,7 @@ query getOrgsForCurrentUser($cursor: String, $first: Int!) {
|
|
|
468
469
|
}
|
|
469
470
|
}
|
|
470
471
|
}
|
|
471
|
-
`,variables:{cursor:e.cursor,first:
|
|
472
|
+
`,variables:{cursor:e.cursor,first:v}},t);if(!n.body.data)throw new h("Could not fetch orgs for current user",n.body.errors);let o=n.body.data.viewer.organizations.nodes||[];return{pageInfo:n.body.data.viewer.organizations.pageInfo,data:o.map(i=>({id:i.databaseId.toString(),graphQLId:i.id,username:i.login,name:i.name||null,email:i.email||null,avatarUrl:i.avatarUrl}))}}async getOrgMembers(e,t={}){let n=await f(this.config,{query:`
|
|
472
473
|
query getOrgMember($cursor: String, $first: Int!, $login: String!) {
|
|
473
474
|
viewer {
|
|
474
475
|
organization(login: $login) {
|
|
@@ -478,28 +479,28 @@ query getOrgMember($cursor: String, $first: Int!, $login: String!) {
|
|
|
478
479
|
hasNextPage
|
|
479
480
|
}
|
|
480
481
|
nodes {
|
|
481
|
-
${
|
|
482
|
+
${U(!1,!0)}
|
|
482
483
|
}
|
|
483
484
|
}
|
|
484
485
|
}
|
|
485
486
|
}
|
|
486
487
|
}
|
|
487
|
-
`,variables:{cursor:e.cursor,first:
|
|
488
|
+
`,variables:{cursor:e.cursor,first:v,login:e.org}},t);if(!n.body.data?.viewer.organization?.membersWithRole&&n.body.errors?.length)throw new h("Could not read the members of the organization",n.body.errors);let o=n.body.data?.viewer.organization?.membersWithRole.nodes||[];return{pageInfo:{hasNextPage:n.body.data?.viewer.organization?.membersWithRole.pageInfo.hasNextPage??!1,endCursor:n.body.data?.viewer.organization?.membersWithRole.pageInfo.endCursor??null},data:o.map(i=>T({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)}))}}async getRepo(e,t={}){let n=await f(this.config,{query:`
|
|
488
489
|
query getRepo($owner: String!, $name: String!) {
|
|
489
490
|
repository(owner: $owner, name: $name) {
|
|
490
|
-
${
|
|
491
|
+
${ot}
|
|
491
492
|
}
|
|
492
493
|
}
|
|
493
|
-
`,variables:{owner:e.namespace,name:e.name}},t);if(!n.body.data?.repository)throw new h(`Repository ${e.namespace}/${e.name} not found`,n.body.errors);return{data:
|
|
494
|
+
`,variables:{owner:e.namespace,name:e.name}},t);if(!n.body.data?.repository)throw new h(`Repository ${e.namespace}/${e.name} not found`,n.body.errors);return{data:it(n.body.data.repository)}}async getRepos(e,t={}){let n=e.map(({namespace:u,name:l},p)=>`
|
|
494
495
|
getRepo_${p}: repository(owner: "${u}", name: "${l}") {
|
|
495
|
-
${
|
|
496
|
+
${ot}
|
|
496
497
|
}
|
|
497
498
|
`).join(`
|
|
498
499
|
`),o=await f(this.config,{query:`
|
|
499
500
|
query batchGetRepos {
|
|
500
501
|
${n}
|
|
501
502
|
}
|
|
502
|
-
`},t);if(!o.body.data)throw new h("Could not fetch repos",o.body.errors);let i=[],a=[];return e.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?i.push(
|
|
503
|
+
`},t);if(!o.body.data)throw new h("Could not fetch repos",o.body.errors);let i=[],a=[];return e.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?i.push(it(p)):a.push({input:u})}),{data:i,errors:a}}async fetchMultipleRESTPages(e,t,n,o){let i=[];for(let d=0;d<t;d++)i.push(n(e+d));let a=await Promise.all(i),u=[];for(let d of a){if(!d.body)throw new Error(d.statusText||"Unknown error");u=u.concat(d.body.map(c=>o(c)))}let l=a.every(d=>d.body.length===100),p=e+t;return{data:u,pageInfo:{hasNextPage:l,nextPage:l?p:null}}}async getReposForCurrentUser(e,t={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForCurrentUser'");let n=new URLSearchParams;n.append("per_page","100"),e.affiliations&&n.append("affiliation",e.affiliations.join(","));let o=i=>this.config.request({url:`${K(this.config,t)}/user/repos?${n.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,tr)}async getReposForOrg(e,t={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForOrg'");let n=o=>this.config.request({url:`${K(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,n,tr)}async getReposForUsernames(e,t={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let n=await f(this.config,{query:`
|
|
503
504
|
query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
|
|
504
505
|
search(query: $query, type: REPOSITORY, first: $first, after: $cursor) {
|
|
505
506
|
pageInfo {
|
|
@@ -508,12 +509,12 @@ query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
|
|
|
508
509
|
}
|
|
509
510
|
nodes {
|
|
510
511
|
... on Repository {
|
|
511
|
-
${
|
|
512
|
+
${ot}
|
|
512
513
|
}
|
|
513
514
|
}
|
|
514
515
|
}
|
|
515
516
|
}
|
|
516
|
-
`,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:
|
|
517
|
+
`,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:v}},t);if(!n.body.data)throw new h("Could not fetch repos for usernames",n.body.errors);let o=n.body.data.search.nodes||[];return{pageInfo:n.body.data.search.pageInfo,data:o.map(it)}}async getReposForOwners(e,t={}){return this.getReposForUsernames({usernames:e.owners.filter(n=>n.username).map(n=>n.username),cursor:e.cursor},t)}async getRefs(e,t,n={}){let o=await f(this.config,{query:`
|
|
517
518
|
query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: String, $first: Int!) {
|
|
518
519
|
repository(owner: $owner, name: $name) {
|
|
519
520
|
refs(refPrefix: $refPrefix first: $first after: $cursor) {
|
|
@@ -534,7 +535,7 @@ query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: Str
|
|
|
534
535
|
}
|
|
535
536
|
}
|
|
536
537
|
}
|
|
537
|
-
`,variables:{owner:t.repo.namespace,name:t.repo.name,refPrefix:e,cursor:t.cursor,first:
|
|
538
|
+
`,variables:{owner:t.repo.namespace,name:t.repo.name,refPrefix:e,cursor:t.cursor,first:v}},n),i=o.body.data?.repository;if(!i)throw new h("Ref repository not found.",o.body.errors);let a=i.refs;return a?{pageInfo:a.pageInfo,data:(a.nodes||[]).map(u=>{let l=u.target?.oid?u.target:null;return{name:u.name,commit:l?{oid:l.oid,authoredDate:new Date(l.authoredDate),committedDate:new Date(l.committedDate)}:null}})}:{pageInfo:{endCursor:null,hasNextPage:!1},data:[]}}async getBranches(e,t={}){return this.getRefs("refs/heads/",e,t)}async getTags(e,t={}){return this.getRefs("refs/tags/",e,t)}async getBlame(e,t={}){let n=await f(this.config,{query:`
|
|
538
539
|
query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
539
540
|
repository(owner: $owner, name: $name) {
|
|
540
541
|
object(expression: $ref) {
|
|
@@ -573,7 +574,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
573
574
|
}
|
|
574
575
|
}
|
|
575
576
|
}
|
|
576
|
-
`,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},t),o=n.body.data?.repository;if(!o)throw new h("Blame repository not found.",n.body.errors);let i=o.object;if(!i||!("blame"in i))throw new h("Ref not found.",n.body.errors);if(i.blame.ranges.length===0)throw new h("File not found.",n.body.errors);return{data:{ranges:i.blame.ranges.map(a=>({startingLine:a.startingLine,endingLine:a.endingLine,commit:{oid:a.commit.oid,parentOids:a.commit.parents.nodes?.map(u=>u.oid)||[],authoredDate:new Date(a.commit.authoredDate),author:a.commit.author?{name:a.commit.author.name,email:a.commit.author.email,avatarUrl:a.commit.author.avatarUrl}:null,committedDate:new Date(a.commit.committedDate),committer:a.commit.committer?{name:a.commit.committer.name,email:a.commit.committer.email,avatarUrl:a.commit.committer.avatarUrl}:null,message:a.commit.message,fileCount:a.commit.changedFilesIfAvailable,additions:a.commit.additions,deletions:a.commit.deletions}}))}}}async getFileContents(e,t={}){let n=await this.config.request({url:`${
|
|
577
|
+
`,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},t),o=n.body.data?.repository;if(!o)throw new h("Blame repository not found.",n.body.errors);let i=o.object;if(!i||!("blame"in i))throw new h("Ref not found.",n.body.errors);if(i.blame.ranges.length===0)throw new h("File not found.",n.body.errors);return{data:{ranges:i.blame.ranges.map(a=>({startingLine:a.startingLine,endingLine:a.endingLine,commit:{oid:a.commit.oid,parentOids:a.commit.parents.nodes?.map(u=>u.oid)||[],authoredDate:new Date(a.commit.authoredDate),author:a.commit.author?{name:a.commit.author.name,email:a.commit.author.email,avatarUrl:a.commit.author.avatarUrl}:null,committedDate:new Date(a.commit.committedDate),committer:a.commit.committer?{name:a.commit.committer.name,email:a.commit.committer.email,avatarUrl:a.commit.committer.avatarUrl}:null,message:a.commit.message,fileCount:a.commit.changedFilesIfAvailable,additions:a.commit.additions,deletions:a.commit.deletions}}))}}}async getFileContents(e,t={}){let n=await this.config.request({url:`${K(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(n.headers["content-type"].startsWith("application/json"))throw new Error(`GitHub: got directory when fetching "${e.path}", getFileContents does not support fetching directories`);if(!n.headers["content-type"].startsWith("application/vnd.github.raw+json"))throw new Error(`GitHub: unsupported content type "${n.headers["content-type"]}" when fetching "${e.path}"`);return{data:new Blob([n.body])}}async getMergeBase(e,t={}){return{data:(await this.config.request({url:`${K(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 searchPullRequests(e,t={}){let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=F(o),a=p=>{let d=p&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return nt("pr",d,e.cursor,{maxPageSize:e.maxPageSize??jt,supportsEmail:i,supportsDrafts:p,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await f(this.config,a(!0),t);u.body.errors&&Ce(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await f(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new h("Could not search pull requests",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:l.search.nodes?.filter(D).map(at)||[]}}async searchIssues(e,t={}){let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=F(o),a=await f(this.config,nt("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??Bt,enterpriseVersion:n}),t),{data:u}=a.body;if(!u)throw new h("Could not search issues",a.body.errors);return{pageInfo:{hasNextPage:u.search.pageInfo.hasNextPage,endCursor:u.search.pageInfo.endCursor},data:u.search.nodes?.filter(D).map(Ss)||[]}}async getPullRequestsAssociatedWithUser(e,t={}){let n=[`involves:${e.username}`];return e.repos?.length&&e.repos.forEach(o=>{n.push(`repo:${o.namespace}/${o.name}`)}),e.labelNames&&e.labelNames.forEach(o=>{n.push(`label:"${o}"`)}),this.searchPullRequests({query:n.join(" "),cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)}async getPullRequestsForRepos(e,t={}){let{assigneeLogins:n,updatedBefore:o,authorLogin:i,repos:a,reviewRequestedLogin:u,startQuery:l,mentionLogin:p,labelNames:d,maxPageSize:c}=e,g=st(l||"");return a.forEach(m=>{g.push(`repo:${m.namespace}/${m.name}`)}),n&&n.forEach(m=>{g.push(`assignee:${m}`)}),o&&g.push(`updated:<${o}`),i&&g.push(`author:${i}`),u&&g.push(`review-requested:${u}`),p&&g.push(`mentions:${p}`),d&&d.forEach(m=>{g.push(`label:"${m}"`)}),this.searchPullRequests({query:`sort:updated ${g.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:c},t)}async getPullRequestForRepo(e,t={}){let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=F(o),a=d=>({query:`query getPullRequest(
|
|
577
578
|
$owner: String!
|
|
578
579
|
$name: String!
|
|
579
580
|
$number: Int!
|
|
@@ -583,18 +584,18 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
583
584
|
name: $name
|
|
584
585
|
) {
|
|
585
586
|
pullRequest(number: $number) {
|
|
586
|
-
${
|
|
587
|
+
${Ee(d,i,n)}
|
|
587
588
|
}
|
|
588
589
|
}
|
|
589
|
-
}`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await f(this.config,a(!0),t);u.body.errors&&
|
|
590
|
+
}`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await f(this.config,a(!0),t);u.body.errors&&Ce(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await f(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new h("Could not fetch pull request by number",u.body.errors);let p=u.body.data?.repository.pullRequest;return{data:p?at(p):null}}async getPullRequestByGraphQLId(e,t={}){let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=F(o),a=d=>({query:`query getPullRequest(
|
|
590
591
|
$graphQLId: ID!
|
|
591
592
|
) {
|
|
592
593
|
node(id: $graphQLId) {
|
|
593
594
|
... on PullRequest {
|
|
594
|
-
${
|
|
595
|
+
${Ee(d,i,n)}
|
|
595
596
|
}
|
|
596
597
|
}
|
|
597
|
-
}`,variables:{graphQLId:e.graphQLId}}),u=await f(this.config,a(!0),t);u.body.errors&&
|
|
598
|
+
}`,variables:{graphQLId:e.graphQLId}}),u=await f(this.config,a(!0),t);u.body.errors&&Ce(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await f(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new h("Could not fetch pull request by id",u.body.errors);let p=u.body.data?.node;return{data:p?at(p):null}}async closePullRequest(e,t={}){let{pullRequest:{graphQLId:n}}=e;if(!n)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ClosePullRequest($pullRequestGraphQLId: ID!) {
|
|
598
599
|
closePullRequest(input: { pullRequestId: $pullRequestGraphQLId }) {
|
|
599
600
|
pullRequest {
|
|
600
601
|
id
|
|
@@ -667,7 +668,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
667
668
|
}
|
|
668
669
|
}
|
|
669
670
|
}
|
|
670
|
-
}`,a=await f(this.config,{query:i,variables:{subjectId:n.graphQLId,body:o}},t);if(!a.body.data?.addComment?.commentEdge?.node?.id)throw new h("Could not add comment to pull request",a.body.errors)}async addInlineCommentToPullRequest(e,t={}){let{pullRequest:n,comment:o,path:i,line:a,side:u="RIGHT",threadId:l}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o?.trim())throw new Error("GitHub requires a comment when adding an inline comment to a pull request.");if(l)return this.addReplyToReviewThread({threadId:l,comment:o},t);if(!i?.trim())throw new Error("GitHub requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(a)||a<1)throw new Error("GitHub requires a positive line number when adding an inline comment to a pull request.");if(u!=="LEFT"&&u!=="RIGHT")throw new Error('GitHub requires side to be either "LEFT" or "RIGHT".');return this.createReviewThread({pullRequest:n,comment:o,path:i,line:a,side:u},t)}async deleteInlineComment(e,t={}){let{commentId:n}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');let o=await f(this.config,{query:
|
|
671
|
+
}`,a=await f(this.config,{query:i,variables:{subjectId:n.graphQLId,body:o}},t);if(!a.body.data?.addComment?.commentEdge?.node?.id)throw new h("Could not add comment to pull request",a.body.errors)}async addInlineCommentToPullRequest(e,t={}){let{pullRequest:n,comment:o,path:i,line:a,side:u="RIGHT",threadId:l}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o?.trim())throw new Error("GitHub requires a comment when adding an inline comment to a pull request.");if(l)return this.addReplyToReviewThread({threadId:l,comment:o},t);if(!i?.trim())throw new Error("GitHub requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(a)||a<1)throw new Error("GitHub requires a positive line number when adding an inline comment to a pull request.");if(u!=="LEFT"&&u!=="RIGHT")throw new Error('GitHub requires side to be either "LEFT" or "RIGHT".');return this.createReviewThread({pullRequest:n,comment:o,path:i,line:a,side:u},t)}async deleteInlineComment(e,t={}){let{commentId:n}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');let o=await f(this.config,{query:Vt,variables:{pullRequestReviewCommentId:n}},t);if(!o.body.data?.deletePullRequestReviewComment)throw new h("Could not delete inline comment",o.body.errors)}async deleteComment(e,t={}){let{commentId:n}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');let o=await f(this.config,{query:Jt,variables:{issueCommentId:n}},t);if(!o.body.data?.deleteIssueComment)throw new h("Could not delete comment",o.body.errors)}async editComment(e,t={}){let{commentId:n,body:o}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');if(!o?.trim())throw new Error("GitHub requires a body when editing a comment.");let i=await f(this.config,{query:Kt,variables:{issueCommentId:n,body:o}},t);if(!i.body.data?.updateIssueComment?.issueComment?.id)throw new h("Could not edit comment",i.body.errors)}async editInlineComment(e,t={}){let{commentId:n,body:o}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');if(!o?.trim())throw new Error("GitHub requires a body when editing an inline comment.");let i=await f(this.config,{query:Yt,variables:{pullRequestReviewCommentId:n,body:o}},t);if(!i.body.data?.updatePullRequestReviewComment?.pullRequestReviewComment?.id)throw new h("Could not edit inline comment",i.body.errors)}async resolveReviewThread(e,t={}){let{threadId:n}=e;if(!n)throw new Error('GitHub requires "threadId" for this function.');let o=await f(this.config,{query:Xt,variables:{pullRequestReviewThreadId:n}},t);if(!o.body.data?.resolveReviewThread?.thread?.id)throw new h("Could not resolve review thread",o.body.errors)}async unresolveReviewThread(e,t={}){let{threadId:n}=e;if(!n)throw new Error('GitHub requires "threadId" for this function.');let o=await f(this.config,{query:Zt,variables:{pullRequestReviewThreadId:n}},t);if(!o.body.data?.unresolveReviewThread?.thread?.id)throw new h("Could not unresolve review thread",o.body.errors)}async addReplyToReviewThread(e,t){let{threadId:n,comment:o}=e,i=`mutation AddPullRequestReviewThreadReply(
|
|
671
672
|
$threadId: ID!,
|
|
672
673
|
$body: String!
|
|
673
674
|
) {
|
|
@@ -769,7 +770,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
769
770
|
login
|
|
770
771
|
}
|
|
771
772
|
body
|
|
772
|
-
${!n||
|
|
773
|
+
${!n||x(n,"PR_REVIEW_COMMENT_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
773
774
|
diffHunk
|
|
774
775
|
id
|
|
775
776
|
path
|
|
@@ -789,7 +790,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
789
790
|
login
|
|
790
791
|
}
|
|
791
792
|
body
|
|
792
|
-
${!n||
|
|
793
|
+
${!n||x(n,"PR_REVIEW_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
793
794
|
id
|
|
794
795
|
publishedAt
|
|
795
796
|
url
|
|
@@ -797,13 +798,13 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
797
798
|
}
|
|
798
799
|
}
|
|
799
800
|
}
|
|
800
|
-
}`,l=await f(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},t),p=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(
|
|
801
|
+
}`,l=await f(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},t),p=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(D).reduce((c,g)=>{if(!g.comments.nodes?.[0]?.pullRequestReview)return c;let m=g.comments.nodes[0].pullRequestReview,b=Ps(g);return b&&(c[m.id]||(c[m.id]=[]),c[m.id].push(b)),c},{})??{};return{data:l.body.data?.repository.pullRequest.reviews.nodes?.filter(D).filter(c=>p[c.id]).map(c=>({author:c.author?{avatarUrl:c.author.avatarUrl,email:null,name:c.author.login}:null,body:c.body,createdAt:c.publishedAt?new Date(c.publishedAt):null,id:c.fullDatabaseId??c.databaseId.toString(),graphQLId:c.id,reviewComments:p[c.id],url:c.url}))??[]}}async getCommentsForPullRequest(e,t={}){let n=await this.getEnterpriseVersion(t),o=!n||x(n,"ISSUE_FULL_DATABASE_ID"),{repo:{namespace:i,name:a},pullRequestNumber:u,cursor:l}=e,p=await f(this.config,{query:er(o),variables:{namespace:i,name:a,pullRequestNumber:u,cursor:l,first:v}},t),d=p.body.data?.repository;if(!d)throw new h("Could not fetch pull request comments",p.body.errors);return{data:d.pullRequest.comments.nodes?.filter(D).map(Wt)??[],pageInfo:d.pullRequest.comments.pageInfo}}async getIssuesAssociatedWithUser(e,t={}){let[n,o]=e.cursor?.split(";")||[void 0,void 0],i=[];e.labelNames&&e.labelNames.forEach(c=>{i.push(`label:"${c}"`)});let[a,u]=await Promise.all([n==="null"?null:this.searchIssues({query:`author:${e.username} ${i.join(" ")}`,cursor:n,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t),o==="null"?null:this.searchIssues({query:`assignee:${e.username} ${i.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)]),l={},p=[],d=c=>{l[c.id]||(l[c.id]=!0,p.push(c))};return a?.data.forEach(d),u?.data.forEach(d),{pageInfo:{hasNextPage:a?.pageInfo.hasNextPage||u?.pageInfo.hasNextPage||!1,endCursor:`${a?.pageInfo.hasNextPage&&a?.pageInfo.endCursor||"null"};${u?.pageInfo.hasNextPage&&u?.pageInfo.endCursor||"null"}`},data:p}}async setPullRequestLabels(e,t={}){let{pullRequest:n,labels:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestLabels($pullRequestGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
|
|
801
802
|
updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, labelIds: $labelGraphQLIds }) {
|
|
802
803
|
pullRequest {
|
|
803
804
|
id
|
|
804
805
|
}
|
|
805
806
|
}
|
|
806
|
-
}`,a=await f(this.config,{query:i,variables:{pullRequestGraphQLId:n.graphQLId,labelGraphQLIds:o.map(u=>{if(!u.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return u.graphQLId})}},t);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new h("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,t={}){let n=
|
|
807
|
+
}`,a=await f(this.config,{query:i,variables:{pullRequestGraphQLId:n.graphQLId,labelGraphQLIds:o.map(u=>{if(!u.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return u.graphQLId})}},t);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new h("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,t={}){let n=st(e.startQuery||""),{cursor:o,assigneeLogins:i,updatedBefore:a,authorLogin:u,mentionLogin:l,labelNames:p}=e;return e.repos.forEach(d=>{n.push(`repo:${d.namespace}/${d.name}`)}),i&&i.forEach(d=>{n.push(`assignee:${d}`)}),a&&n.push(`updated:<${a}`),u&&n.push(`author:${u}`),l&&n.push(`mentions:${l}`),p&&p.forEach(d=>{n.push(`label:"${d}"`)}),this.searchIssues({query:`sort:updated ${n.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)}async closeIssueWithReason(e,t={}){let{issue:n,reason:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation CloseIssueWithReason($issueGraphQLId: ID!, $reason: IssueClosedStateReason!) {
|
|
807
808
|
closeIssue(input: { issueId: $issueGraphQLId, stateReason: $reason }) {
|
|
808
809
|
issue {
|
|
809
810
|
id
|
|
@@ -844,7 +845,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
|
|
|
844
845
|
repository(owner: $owner, name: $name) {
|
|
845
846
|
milestones(first: $first, after: $cursor) {
|
|
846
847
|
nodes {
|
|
847
|
-
${
|
|
848
|
+
${ve}
|
|
848
849
|
}
|
|
849
850
|
pageInfo {
|
|
850
851
|
endCursor
|
|
@@ -853,12 +854,12 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
|
|
|
853
854
|
}
|
|
854
855
|
}
|
|
855
856
|
}
|
|
856
|
-
`,variables:{owner:n,name:o,cursor:i,first:
|
|
857
|
+
`,variables:{owner:n,name:o,cursor:i,first:v}},t);if(!a.body.data)throw new h("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(lt)??[]}}async getLabelsForRepo(e,t={}){let{repo:{namespace:n,name:o},cursor:i}=e,a=await f(this.config,{query:`
|
|
857
858
|
query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
|
|
858
859
|
repository(owner: $owner, name: $name) {
|
|
859
860
|
labels(first: $first, after: $cursor) {
|
|
860
861
|
nodes {
|
|
861
|
-
${
|
|
862
|
+
${qe}
|
|
862
863
|
}
|
|
863
864
|
pageInfo {
|
|
864
865
|
endCursor
|
|
@@ -867,7 +868,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
|
|
|
867
868
|
}
|
|
868
869
|
}
|
|
869
870
|
}
|
|
870
|
-
`,variables:{owner:n,name:o,cursor:i,first:
|
|
871
|
+
`,variables:{owner:n,name:o,cursor:i,first:v}},t);if(!a.body.data)throw new h("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(ut)??[]}}async getTreeForRepo(e,t={}){let n=await this.config.request({url:`${K(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...R(t.token||this.config.token)}});if(!n.body)throw new Error("Could not fetch trees");return{data:n.body.tree.map(fs)}}};var vs="https://gitlab.com/api/v4",qs="https://gitlab.com/api/graphql",pt=/\/api\/v\d+$/,sr=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.")},Le=(r,s)=>{let e=s.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),sr(e),pt.test(e)||(e=e+"/api/v4"),e):vs},Es=(r,s)=>{let e=s.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),sr(e),pt.test(e)&&(e=e.replace(pt,"")),`${e}/api/graphql`):qs},P=(r,s,e)=>{let t=R(e.token||r.token);return r.request({url:Es(r,e),method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify(s)})},De=r=>r?.map(s=>`"${s.message}"`).join(", ");var ht=r=>r.split("/").slice(0,-1).join("/"),ft=r=>r.split("/").at(-1)??"",$e=r=>({id:r.id.replace(ne,""),graphQLId:r.id,namespace:ht(r.fullPath),name:ft(r.fullPath),webUrl:r.webUrl}),nr=r=>({id:r.id.replace(ne,""),graphQLId:r.id,httpsUrl:r.httpUrlToRepo,namespace:ht(r.fullPath),name:ft(r.fullPath),sshUrl:r.sshUrlToRepo,webUrl:r.webUrl}),Cs={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},Ls={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var Ds="gid://gitlab/User/",ne="gid://gitlab/Project/",$s="gid://gitlab/MergeRequest/",Us="gid://gitlab/Issue/",As="gid://gitlab/ProjectLabel/",Gs="gid://gitlab/Milestone/",Ts="gid://gitlab/Ci::Build/",Rt=`
|
|
871
872
|
description
|
|
872
873
|
dueDate
|
|
873
874
|
id
|
|
@@ -876,7 +877,7 @@ startDate
|
|
|
876
877
|
state
|
|
877
878
|
title
|
|
878
879
|
webPath
|
|
879
|
-
`,
|
|
880
|
+
`,dt=`
|
|
880
881
|
id
|
|
881
882
|
fullPath
|
|
882
883
|
webUrl
|
|
@@ -890,25 +891,25 @@ userPermissions {
|
|
|
890
891
|
downloadCode
|
|
891
892
|
pushCode
|
|
892
893
|
}
|
|
893
|
-
`,
|
|
894
|
+
`,Q=`
|
|
894
895
|
id
|
|
895
896
|
name
|
|
896
897
|
username
|
|
897
898
|
publicEmail
|
|
898
899
|
avatarUrl
|
|
899
900
|
webUrl
|
|
900
|
-
`,
|
|
901
|
+
`,It=`
|
|
901
902
|
color
|
|
902
903
|
description
|
|
903
904
|
id
|
|
904
905
|
title
|
|
905
|
-
`,
|
|
906
|
+
`,ct=`
|
|
906
907
|
author {
|
|
907
|
-
${
|
|
908
|
+
${Q}
|
|
908
909
|
}
|
|
909
910
|
assignees {
|
|
910
911
|
nodes {
|
|
911
|
-
${
|
|
912
|
+
${Q}
|
|
912
913
|
}
|
|
913
914
|
}
|
|
914
915
|
closedAt
|
|
@@ -919,7 +920,7 @@ id
|
|
|
919
920
|
iid
|
|
920
921
|
labels {
|
|
921
922
|
nodes {
|
|
922
|
-
${
|
|
923
|
+
${It}
|
|
923
924
|
}
|
|
924
925
|
}
|
|
925
926
|
state
|
|
@@ -930,9 +931,9 @@ upvotes
|
|
|
930
931
|
userNotesCount
|
|
931
932
|
webUrl
|
|
932
933
|
milestone {
|
|
933
|
-
${
|
|
934
|
+
${Rt}
|
|
934
935
|
}
|
|
935
|
-
`,
|
|
936
|
+
`,Os=`
|
|
936
937
|
stages {
|
|
937
938
|
nodes {
|
|
938
939
|
jobs {
|
|
@@ -948,11 +949,11 @@ stages {
|
|
|
948
949
|
name
|
|
949
950
|
}
|
|
950
951
|
}
|
|
951
|
-
`,
|
|
952
|
+
`,or=(r,s,e)=>`
|
|
952
953
|
id
|
|
953
954
|
state
|
|
954
955
|
author {
|
|
955
|
-
${
|
|
956
|
+
${Q}
|
|
956
957
|
}
|
|
957
958
|
diffRefs {
|
|
958
959
|
baseSha
|
|
@@ -978,12 +979,12 @@ targetBranch
|
|
|
978
979
|
sourceBranch
|
|
979
980
|
assignees {
|
|
980
981
|
nodes {
|
|
981
|
-
${
|
|
982
|
+
${Q}
|
|
982
983
|
}
|
|
983
984
|
}
|
|
984
985
|
reviewers {
|
|
985
986
|
nodes {
|
|
986
|
-
${
|
|
987
|
+
${Q}
|
|
987
988
|
mergeRequestInteraction {
|
|
988
989
|
approved
|
|
989
990
|
reviewState
|
|
@@ -993,19 +994,19 @@ reviewers {
|
|
|
993
994
|
mergeStatusEnum
|
|
994
995
|
labels {
|
|
995
996
|
nodes {
|
|
996
|
-
${
|
|
997
|
+
${It}
|
|
997
998
|
}
|
|
998
999
|
}
|
|
999
1000
|
${r?"project { id httpUrlToRepo fullPath sshUrlToRepo webUrl archived } sourceProject { id httpUrlToRepo fullPath sshUrlToRepo webUrl }":""}
|
|
1000
|
-
${s?`milestone { ${
|
|
1001
|
-
${e?`headPipeline { ${
|
|
1002
|
-
`,
|
|
1001
|
+
${s?`milestone { ${Rt} }`:""}
|
|
1002
|
+
${e?`headPipeline { ${Os} }`:""}
|
|
1003
|
+
`,H=r=>`${r.namespace}/${r.name}`,xs=r=>`${r.namespace}/${r.name}`,ks=r=>({canCreateWebhook:r.adminOperations,canPush:r.pushCode,isAdmin:r.adminOperations}),gt=r=>({id:r.id.replace(ne,""),graphQLId:r.id,namespace:ht(r.fullPath),name:ft(r.fullPath),webUrl:r.webUrl,httpsUrl:r.httpUrlToRepo,sshUrl:r.sshUrlToRepo,defaultBranch:r.repository?.rootRef?{name:r.repository.rootRef}:null,permissions:ks(r.userPermissions)}),Ns=r=>({path:r.path,isDirectory:r.type==="tree"}),_s={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},ar=(r,s,e)=>!s&&r?.startsWith("/")?`https://gitlab.com${r}`:s&&r?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${r}`:r,j=(r,s,e)=>{let t=ar(r.avatarUrl,s,e);return{id:r.id.replace(Ds,""),graphQLId:r.id,name:r.name,username:r.username,email:r.publicEmail??null,avatarUrl:t,url:r.webUrl}},bt=r=>({color:r.color,description:r.description,id:r.id.replace(As,""),graphQLId:r.id,name:r.title}),Fs=(r,s)=>r?r==="FAILED"&&s?"WARNING":{CANCELED:"CANCELLED",CREATED:"PENDING",FAILED:"FAILED",MANUAL:"OPTIONAL_ACTION_REQUIRED",PENDING:"PENDING",PREPARING:"RUNNING",RUNNING:"RUNNING",SCHEDULED:"PENDING",SKIPPED:"SKIPPED",SUCCESS:"SUCCESS",WAITING_FOR_CALLBACK:"PENDING",WAITING_FOR_RESOURCE:"PENDING"}[r]:null,Qs=(r,s,e)=>{let t={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:j(r,s,e),state:r.mergeRequestInteraction?.reviewState?t[r.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},ir=(r,s,e,t,n)=>{let o=r.reviewers?.nodes?r.reviewers.nodes.map(i=>Qs(i,t,n)):null;return{id:r.id.replace($s,""),graphQLId:r.id,title:r.title,description:r.description,number:parseInt(r.iid,10),state:_s[r.state],commentCount:r.userNotesCount||0,upvoteCount:r.upvotes,author:r.author?j(r.author,t,n):null,createdDate:new Date(r.createdAt),isDraft:r.draft,repository:{id:s.id,graphQLId:s.graphQLId,name:s.name,owner:{login:s.namespace},remoteInfo:s.httpsUrl&&s.sshUrl?{cloneUrlHTTPS:s.httpsUrl,cloneUrlSSH:s.sshUrl}:null},headRepository:e?{id:e.id,graphQLId:e.graphQLId,name:e.name,owner:{login:e.namespace},remoteInfo:{cloneUrlHTTPS:e.httpsUrl,cloneUrlSSH:e.sshUrl}}:null,headCommit:{buildStatuses:r.headPipeline?.stages?.nodes?.flatMap(i=>i.jobs?.nodes?.map(a=>({completedAt:a.finishedAt?new Date(a.finishedAt):null,description:null,name:a.name??null,state:Fs(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${s.webUrl}/-/jobs/${a.id.replace(Ts,"")}`}))??[])??[]},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=>j(i,t,n)):null,reviews:o,reviewDecision:O(o),additions:r.diffStatsSummary?.additions||0,deletions:r.diffStatsSummary?.deletions||0,fileCount:r.diffStatsSummary?.fileCount||0,commitCount:r.commitCount||0,mergeableState:Ls[r.mergeStatusEnum],milestone:r.milestone?yt(r.milestone,s.webUrl):null,labels:r.labels?.nodes?.map(bt)??[],permissions:null}},mt=(r,s,e,t)=>({author:j(r.author,e,t),assignees:r.assignees.nodes.map(n=>j(n,e,t)),commentCount:r.userNotesCount,closedDate:r.closedAt?new Date(r.closedAt):null,createdDate:new Date(r.createdAt),description:r.description,graphQLId:r.id,id:r.id.replace(Us,""),labels:r.labels?.nodes?.map(bt)??[],number:r.iid,repository:{id:s.id.replace(ne,""),graphQLId:s.id,name:s.name,owner:{login:s.namespace}},updatedDate:new Date(r.updatedAt),upvoteCount:r.upvotes,state:{name:r.state,color:null},type:r.type,title:r.title,url:r.webUrl,milestone:r.milestone?yt(r.milestone,s.webUrl):null}),yt=(r,s)=>({id:r.id.replace(Gs,""),graphQLId:r.id,number:parseInt(r.iid,10),title:r.title,description:r.description,isOpen:r.state==="active",url:`${s}/-/${r.webPath.replace(/.+?\/-\//,"")}`,startDate:r.startDate?new Date(r.startDate):null,dueDate:r.dueDate?new Date(r.dueDate):null}),oe=class extends ${getIsSelfHosted(s){return!!s.baseUrl||!!this.config.baseUrl}async getCurrentUser(s={},e={}){let n=(await P(this.config,{query:`
|
|
1003
1004
|
query getCurrentUser {
|
|
1004
1005
|
currentUser {
|
|
1005
|
-
${
|
|
1006
|
+
${Q}
|
|
1006
1007
|
}
|
|
1007
1008
|
}
|
|
1008
|
-
`},e)).body.data?.currentUser;if(!n)throw new Error("Current user not found.");return{data:
|
|
1009
|
+
`},e)).body.data?.currentUser;if(!n)throw new Error("Current user not found.");return{data:j(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getUserForCommit(s,e={}){let t=H(s.repo),o=(await P(this.config,{query:`
|
|
1009
1010
|
query getUserForCommit($fullPath: ID!, $oid: String!) {
|
|
1010
1011
|
project(fullPath: $fullPath) {
|
|
1011
1012
|
repository {
|
|
@@ -1021,21 +1022,21 @@ query getUserForCommit($fullPath: ID!, $oid: String!) {
|
|
|
1021
1022
|
}
|
|
1022
1023
|
}
|
|
1023
1024
|
}
|
|
1024
|
-
`,variables:{fullPath:t,oid:s.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=
|
|
1025
|
+
`,variables:{fullPath:t,oid:s.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=ar(o.author.avatarUrl,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl);return{data:{name:o.authorName,email:o.authorEmail,avatarUrl:i}}}async getAccountForEmail(s,e={}){let n=(await P(this.config,{query:`
|
|
1025
1026
|
query getAccountForEmail($email: String!) {
|
|
1026
1027
|
users(search: $email) {
|
|
1027
1028
|
nodes {
|
|
1028
|
-
${
|
|
1029
|
+
${Q}
|
|
1029
1030
|
}
|
|
1030
1031
|
}
|
|
1031
1032
|
}
|
|
1032
|
-
`,variables:{email:s.email}},e)).body.data?.users?.nodes?.[0];if(!n)throw new Error("User not found.");return{data:
|
|
1033
|
+
`,variables:{email:s.email}},e)).body.data?.users?.nodes?.[0];if(!n)throw new Error("User not found.");return{data:j(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountForUsername(s,e={}){let n=(await P(this.config,{query:`
|
|
1033
1034
|
query getAccountForUsername($username: String!) {
|
|
1034
1035
|
user(username: $username) {
|
|
1035
|
-
${
|
|
1036
|
+
${Q}
|
|
1036
1037
|
}
|
|
1037
1038
|
}
|
|
1038
|
-
`,variables:{username:s.username}},e)).body.data?.user;if(!n)throw new Error("User not found.");return{data:
|
|
1039
|
+
`,variables:{username:s.username}},e)).body.data?.user;if(!n)throw new Error("User not found.");return{data:j(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountsForRepo(s,e={}){let{repo:{namespace:t,name:n},cursor:o}=s,i=await P(this.config,{query:`
|
|
1039
1040
|
query getAccountsForRepo(
|
|
1040
1041
|
$fullPath: ID!
|
|
1041
1042
|
$after: String
|
|
@@ -1046,7 +1047,7 @@ query getAccountsForRepo(
|
|
|
1046
1047
|
projectMembers(after: $after) {
|
|
1047
1048
|
nodes {
|
|
1048
1049
|
user {
|
|
1049
|
-
${
|
|
1050
|
+
${Q}
|
|
1050
1051
|
}
|
|
1051
1052
|
}
|
|
1052
1053
|
pageInfo {
|
|
@@ -1056,22 +1057,22 @@ query getAccountsForRepo(
|
|
|
1056
1057
|
}
|
|
1057
1058
|
}
|
|
1058
1059
|
}
|
|
1059
|
-
`,variables:{fullPath:`${t}/${n}`,after:o}},e),a=i.body.data?.project?.projectMembers?.nodes?.map(u=>u.user).filter(u=>u!==null);return{pageInfo:i.body.data?.project?.projectMembers?.pageInfo??{endCursor:null,hasNextPage:!1},data:a?.map(u=>
|
|
1060
|
+
`,variables:{fullPath:`${t}/${n}`,after:o}},e),a=i.body.data?.project?.projectMembers?.nodes?.map(u=>u.user).filter(u=>u!==null);return{pageInfo:i.body.data?.project?.projectMembers?.pageInfo??{endCursor:null,hasNextPage:!1},data:a?.map(u=>j(u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))??[]}}async getRepo(s,e={}){let t=H(s),n=await P(this.config,{query:`
|
|
1060
1061
|
query getRepo($fullPath: ID!) {
|
|
1061
1062
|
project(fullPath: $fullPath) {
|
|
1062
|
-
${
|
|
1063
|
+
${dt}
|
|
1063
1064
|
}
|
|
1064
1065
|
}
|
|
1065
|
-
`,variables:{fullPath:t}},e);if(!n.body.data?.project)throw new Error(`Repository ${t} not found`);return{data:
|
|
1066
|
+
`,variables:{fullPath:t}},e);if(!n.body.data?.project)throw new Error(`Repository ${t} not found`);return{data:gt(n.body.data.project)}}async getReposBase(s,e={}){let n=s.map(H).map((u,l)=>`
|
|
1066
1067
|
getRepo_${l}: project(fullPath: "${u}") {
|
|
1067
|
-
${
|
|
1068
|
+
${dt}
|
|
1068
1069
|
}
|
|
1069
1070
|
`).join(`
|
|
1070
|
-
`),o=await
|
|
1071
|
+
`),o=await P(this.config,{query:`
|
|
1071
1072
|
query batchGetRepos {
|
|
1072
1073
|
${n}
|
|
1073
1074
|
}
|
|
1074
|
-
`},e);if(!o.body.data)throw new Error(
|
|
1075
|
+
`},e);if(!o.body.data)throw new Error(De(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return s.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?i.push(gt(p)):a.push({input:u})}),{data:i,errors:a}}async getRepos(s,e={}){let t=[];for(let i=0;i<s.length;i+=15)t.push(s.slice(i,i+15));return(await Promise.all(t.map(i=>this.getReposBase(i,e)))).reduce((i,a)=>({data:[...i.data,...a.data],errors:[...i.errors,...a.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(s,e={}){let t=await P(this.config,{query:`
|
|
1075
1076
|
query getReposForCurrentUser($after: String) {
|
|
1076
1077
|
projects(membership: true first: 100 after: $after) {
|
|
1077
1078
|
pageInfo {
|
|
@@ -1079,11 +1080,11 @@ query getReposForCurrentUser($after: String) {
|
|
|
1079
1080
|
hasNextPage
|
|
1080
1081
|
}
|
|
1081
1082
|
nodes {
|
|
1082
|
-
${
|
|
1083
|
+
${dt}
|
|
1083
1084
|
}
|
|
1084
1085
|
}
|
|
1085
1086
|
}
|
|
1086
|
-
`,variables:{after:s.cursor}},e);if(!t.body.data?.projects)throw new Error(
|
|
1087
|
+
`,variables:{after:s.cursor}},e);if(!t.body.data?.projects)throw new Error(De(t.body.errors)||t.statusText||"Unknown error");let n=t.body.data?.projects?.nodes||[];return{pageInfo:t.body.data?.projects?.pageInfo,data:n.map(gt)}}async getRefs(s,e,t={}){let n=H(e.repo),o=new URL(`${Le(this.config,t)}/projects/${encodeURIComponent(n)}/repository/${s}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page",v.toString());let i=await this.config.request({url:o.toString(),headers:R(t.token||this.config.token)}),a=i.headers["x-next-page"];return{pageInfo:{hasNextPage:!!a,nextPage:a?parseInt(a,10):null},data:i.body.map(u=>({name:u.name,commit:{oid:u.commit.id,authoredDate:new Date(u.commit.authored_date),committedDate:new Date(u.commit.committed_date)}}))}}async getBranches(s,e={}){return this.getRefs("branches",s,e)}async getTags(s,e={}){return this.getRefs("tags",s,e)}async getBlame(s,e={}){let t=H(s.repo),n=new URL(`${Le(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(s.path)}/blame`);n.searchParams.set("ref",s.ref);let o=await this.config.request({url:n.toString(),headers: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(s,e={}){let t="";s.repo?.id?t=`projectId:"${s.repo.id}"`:s.repo?.namespace&&s.repo?.name&&(t=`projectPath:"${s.repo.namespace}/${s.repo.name}"`);let n=Cs[s.association],o=await P(this.config,{query:`
|
|
1087
1088
|
query getPullRequestsForUser($username: String! $cursor: String $labelNames: [String!]) {
|
|
1088
1089
|
user(username: $username) {
|
|
1089
1090
|
${n}(state:opened first:100 after:$cursor labels: $labelNames${t?` ${t}`:""}) {
|
|
@@ -1092,12 +1093,12 @@ query getPullRequestsForUser($username: String! $cursor: String $labelNames: [St
|
|
|
1092
1093
|
hasNextPage
|
|
1093
1094
|
}
|
|
1094
1095
|
nodes {
|
|
1095
|
-
${
|
|
1096
|
+
${or(!0,!0,!0)}
|
|
1096
1097
|
}
|
|
1097
1098
|
}
|
|
1098
1099
|
}
|
|
1099
1100
|
}
|
|
1100
|
-
`,variables:{username:s.username,cursor:s.cursor,labelNames:s.labelNames}},e);if(!o.body.data)throw new Error(
|
|
1101
|
+
`,variables:{username:s.username,cursor:s.cursor,labelNames:s.labelNames}},e);if(!o.body.data)throw new Error(De(o.body.errors)||o.statusText||"Unknown error");if(!o.body.data.user)throw new Error("User not found");let i=o.body.data.user[n];if(!i)throw new Error("Unexpected response");return{pageInfo:i.pageInfo,data:i.nodes?.filter(a=>s.includeFromArchivedRepos||!a.project.archived).map(a=>ir(a,nr(a.project),nr(a.sourceProject),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))||[]}}async getPullRequestsAssociatedWithUser(s,e={}){let[t,n,o]=s.cursor?.split(";")||[void 0,void 0,void 0],i=t?.split("-")||[],a=n?.split("-")||[],u=o?.split("-")||[],l=[],p=[],d=[],c=0;do{let S=s.repos&&s.repos[c];i[c]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:s.username,association:"authored",cursor:i[c],includeFromArchivedRepos:s.includeFromArchivedRepos,labelNames:s.labelNames,...S&&{repo:S}},e)),a[c]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:s.username,association:"assigned",cursor:a[c],includeFromArchivedRepos:s.includeFromArchivedRepos,labelNames:s.labelNames,...S&&{repo:S}},e)),u[c]==="null"?d.push(null):d.push(this.getPullRequestsForUser({username:s.username,association:"reviewRequested",cursor:u[c],includeFromArchivedRepos:s.includeFromArchivedRepos,labelNames:s.labelNames,...S&&{repo:S}},e)),c++}while(c<(s.repos?.length||0));let g=[l,p,d].flat(),m=await Promise.all(g),b={},I=[],L=S=>{b[S.id]||(b[S.id]=!0,I.push(S))},A=!1,X=m.map((S,q)=>{let _="";return S&&S.data.forEach(L),S?.pageInfo.hasNextPage?(A=!0,_+=`${S.pageInfo.endCursor||"null"}`):_+="null",s.repos?.length&&(q+1)%s.repos.length!==0?_+="-":q+1<m.length&&(_+=";"),_}).join("");return{pageInfo:{hasNextPage:A,endCursor:X},data:I}}getVariablesForPullRequests(s){let{updatedBefore:e,isDraft:t,authorLogin:n,assigneeLogins:o,labelNames:i,reviewRequestedLogin:a}=s||{},u={},l=[],p=[],d=(c,g,m)=>{l.push(`$${c}: ${m}`),p.push(`${c}: $${c}`),u[c]=g};return e&&d("updatedBefore",e,"Time"),n&&d("authorUsername",n,"String"),o&&d("assigneeUsername",o[0],"String"),i&&d("labelName",i,"[String]"),t!=null&&d("draft",t,"Boolean"),a&&d("reviewerUsername",a,"String"),{variables:u,variableTypes:l,mergeRequestArguments:p}}async getPullRequestsForRepoBase(s,e={},t){let{cursor:n,repo:o}=s||{},i=H(o),{variables:a,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(s),p={fullPath:i,...a},d=await P(this.config,{query:`
|
|
1101
1102
|
query getPullRequestsForRepo(
|
|
1102
1103
|
$fullPath: ID!
|
|
1103
1104
|
$after: String
|
|
@@ -1122,19 +1123,19 @@ query getPullRequestsForRepo(
|
|
|
1122
1123
|
hasNextPage
|
|
1123
1124
|
}
|
|
1124
1125
|
nodes {
|
|
1125
|
-
${
|
|
1126
|
+
${or(!1,!0,!0)}
|
|
1126
1127
|
}
|
|
1127
1128
|
}
|
|
1128
1129
|
}
|
|
1129
1130
|
}
|
|
1130
|
-
`,variables:{...p,after:n}},e),c=[],g=d.body.data?.project;if(!t&&g?.archived)return{pageInfo:null,data:[]};let m
|
|
1131
|
+
`,variables:{...p,after:n}},e),c=[],g=d.body.data?.project;if(!t&&g?.archived)return{pageInfo:null,data:[]};let m=$e(g||{id:"",fullPath:"",webUrl:""});return(g?.mergeRequests?.nodes||[]).forEach(I=>{c.push(ir(I,m,null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.mergeRequests?.pageInfo,data:c}}async getPullRequestsForRepo(s,e={}){return this.getPullRequestsForRepoBase(s,e,!1)}async getPullRequestsForRepos(s,e={}){let{repos:t,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l}=s;return{data:(await Promise.all(t.map(d=>this.getPullRequestsForRepoBase({repo:d,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l},e,s.includeFromArchivedRepos??!1)))).flatMap(d=>d.data)}}async closePullRequest(s,e={}){let{pullRequest:t}=s,n=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
|
|
1131
1132
|
mergeRequestUpdate(input: { projectPath: $fullPath, iid: $pullRequestId, state: CLOSED }) {
|
|
1132
1133
|
errors,
|
|
1133
1134
|
mergeRequest {
|
|
1134
1135
|
id
|
|
1135
1136
|
}
|
|
1136
1137
|
}
|
|
1137
|
-
}`,i=(await
|
|
1138
|
+
}`,i=(await P(this.config,{query:n,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString()}},e)).body.data?.mergeRequestUpdate;if(!i?.mergeRequest?.id||i?.errors?.length!==0)throw new Error("Could not close pull request")}async mergePullRequest(s,e={}){let{pullRequest:t,mergeStrategy:n}=s;if(!t.headRef?.oid)throw new Error('GitLab requires "headRef.oid" for this function.');let o=`mutation MergePullRequest(
|
|
1138
1139
|
$fullPath: ID!,
|
|
1139
1140
|
$pullRequestId: String!,
|
|
1140
1141
|
$expectedSourceSha: String!,
|
|
@@ -1151,59 +1152,59 @@ query getPullRequestsForRepo(
|
|
|
1151
1152
|
id
|
|
1152
1153
|
}
|
|
1153
1154
|
}
|
|
1154
|
-
}`,a=(await
|
|
1155
|
+
}`,a=(await P(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),expectedSourceSha:t.headRef.oid,squash:n==="SQUASH"}},e)).body.data?.mergeRequestAccept;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not merge pull request")}async setPullRequestMilestone(s,e={}){let{pullRequest:t,milestone:n}=s;if(!t.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetPullRequestMilestone($fullPath: ID!, $pullRequestId: String!, $milestoneGraphQLId: MilestoneID) {
|
|
1155
1156
|
mergeRequestSetMilestone(input: { projectPath: $fullPath, iid: $pullRequestId, milestoneId: $milestoneGraphQLId }) {
|
|
1156
1157
|
errors,
|
|
1157
1158
|
mergeRequest {
|
|
1158
1159
|
id
|
|
1159
1160
|
}
|
|
1160
1161
|
}
|
|
1161
|
-
}`,i=await
|
|
1162
|
+
}`,i=await P(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),milestoneGraphQLId:n?.graphQLId}},e),a=i.body.data?.mergeRequestSetMilestone;if(!a?.mergeRequest?.id||i.body.errors||a?.errors?.length!==0)throw new Error("Could not set milestone of pull request")}async setPullRequestAsDraft(s,e={}){let{pullRequest:t,isDraft:n}=s,o=`mutation MergeRequestSetDraft($fullPath: ID!, $pullRequestId: String!, $isDraft: Boolean!) {
|
|
1162
1163
|
mergeRequestSetDraft(input: { projectPath: $fullPath, iid: $pullRequestId, draft: $isDraft }) {
|
|
1163
1164
|
errors,
|
|
1164
1165
|
mergeRequest {
|
|
1165
1166
|
id
|
|
1166
1167
|
}
|
|
1167
1168
|
}
|
|
1168
|
-
}`,a=(await
|
|
1169
|
+
}`,a=(await P(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),isDraft:n}},e)).body.data?.mergeRequestSetDraft;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request as draft")}async setPullRequestReviewers(s,e={}){let{pullRequest:t,reviewers:n}=s,o=n.map(l=>{if(!l.username)throw new Error('GitLab requires reviewer "username" for this function.');return l.username}),i=`mutation MergeRequestSetReviewers($fullPath: ID!, $pullRequestId: String!, $reviewerUsernames: [String!]!) {
|
|
1169
1170
|
mergeRequestSetReviewers(input: { projectPath: $fullPath, iid: $pullRequestId, reviewerUsernames: $reviewerUsernames }) {
|
|
1170
1171
|
errors,
|
|
1171
1172
|
mergeRequest {
|
|
1172
1173
|
id
|
|
1173
1174
|
}
|
|
1174
1175
|
}
|
|
1175
|
-
}`,u=(await
|
|
1176
|
+
}`,u=(await P(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),reviewerUsernames:o}},e)).body.data?.mergeRequestSetReviewers;if(!u?.mergeRequest?.id||u?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReview(s,e={}){let{pullRequest:t,reviewer:n}=s;if(!n.graphQLId)throw new Error('GitLab requires reviwer "graphQLId" for this function.');let o=`mutation MergeRequestReviewerRereview($fullPath: ID!, $pullRequestId: String!, $reviewerUserId: UserID!) {
|
|
1176
1177
|
mergeRequestReviewerRereview(input: { projectPath: $fullPath, iid: $pullRequestId, userId: $reviewerUserId }) {
|
|
1177
1178
|
errors,
|
|
1178
1179
|
mergeRequest {
|
|
1179
1180
|
id
|
|
1180
1181
|
}
|
|
1181
1182
|
}
|
|
1182
|
-
}`,a=(await
|
|
1183
|
+
}`,a=(await P(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),reviewerUserId:n.graphQLId}},e)).body.data?.mergeRequestReviewerRereview;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReviews(s,e={}){let{pullRequest:t,reviewers:n}=s,o=t.reviews;if(!o)throw new Error('GitLab requires "reviews" for this function.');let i=n.filter(a=>o.find(u=>u.reviewer.graphQLId===a.graphQLId));await Promise.all(i.map(a=>this.reRequestPullRequestReview({pullRequest:t,reviewer:a},e)))}async setPullRequestAssignees(s,e={}){let{pullRequest:t,assignees:n}=s,o=n.map(l=>{if(!l.username)throw new Error('GitLab requires assignee "username" for this function.');return l.username}),i=`mutation MergeRequestSetAssignees($fullPath: ID!, $pullRequestId: String!, $assigneeUsernames: [String!]!) {
|
|
1183
1184
|
mergeRequestSetAssignees(input: { projectPath: $fullPath, iid: $pullRequestId, assigneeUsernames: $assigneeUsernames }) {
|
|
1184
1185
|
errors,
|
|
1185
1186
|
mergeRequest {
|
|
1186
1187
|
id
|
|
1187
1188
|
}
|
|
1188
1189
|
}
|
|
1189
|
-
}`,u=(await
|
|
1190
|
+
}`,u=(await P(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),assigneeUsernames:o}},e)).body.data?.mergeRequestSetAssignees;if(!u?.mergeRequest?.id||u?.errors?.length!==0)throw new Error("Could not set pull request assignees")}async setPullRequestLabels(s,e={}){let{pullRequest:t,labels:n}=s,o=n.map(u=>{if(!u.graphQLId)throw new Error('GitLab requires "graphQLId" for labels in this function.');return u.graphQLId}),i=`mutation SetPullRequestLabels($fullPath: ID!, $pullRequestId: String!, $labelGraphQLIds: [LabelID!]!) {
|
|
1190
1191
|
mergeRequestSetLabels(input: { projectPath: $fullPath, iid: $pullRequestId, labelIds: $labelGraphQLIds }) {
|
|
1191
1192
|
mergeRequest {
|
|
1192
1193
|
id
|
|
1193
1194
|
}
|
|
1194
1195
|
}
|
|
1195
|
-
}`;if(!(await
|
|
1196
|
+
}`;if(!(await P(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),labelGraphQLIds:o}},e)).body.data?.mergeRequestSetLabels?.mergeRequest?.id)throw new Error("Could not set pull request labels")}async getIssue(s,e={}){let t=xs(s),n=await P(this.config,{query:`
|
|
1196
1197
|
query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
1197
1198
|
project(fullPath: $projectId) {
|
|
1198
1199
|
id
|
|
1199
1200
|
fullPath
|
|
1200
1201
|
webUrl
|
|
1201
1202
|
issue(iid: $issueNumber) {
|
|
1202
|
-
${
|
|
1203
|
+
${ct}
|
|
1203
1204
|
}
|
|
1204
1205
|
}
|
|
1205
1206
|
}
|
|
1206
|
-
`,variables:{issueNumber:s.number,projectId:t}},e);if(!n.body.data?.project)throw new Error(`Repository ${t} not found`);if(!n.body.data?.project?.issue)throw new Error(`Issue ${s.number} not found`);return{data:
|
|
1207
|
+
`,variables:{issueNumber:s.number,projectId:t}},e);if(!n.body.data?.project)throw new Error(`Repository ${t} not found`);if(!n.body.data?.project?.issue)throw new Error(`Issue ${s.number} not found`);return{data:mt(n.body.data.project.issue,$e(n.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(s){let{updatedBefore:e,authorLogin:t,assigneeLogins:n,labelNames:o}=s||{},i={},a=[],u=[],l=(p,d,c)=>{a.push(`$${p}: ${c}`),u.push(`${p}: $${p}`),i[p]=d};return e&&l("updatedBefore",e,"Time"),t&&l("authorUsername",t,"String"),n&&l("assigneeUsername",n[0],"String"),o&&l("labelName",o,"[String]"),{variables:i,variableTypes:a,issueArguments:u}}async getIssuesForRepo(s,e={}){let{cursor:t,repo:n}=s||{},o=H(n),{variables:i,variableTypes:a,issueArguments:u}=this.getVariablesForIssues(s),l={fullPath:o,...i},p=`
|
|
1207
1208
|
query GetIssuesFromProject(
|
|
1208
1209
|
$fullPath: ID!
|
|
1209
1210
|
$after: String
|
|
@@ -1223,7 +1224,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1223
1224
|
${u.length?u.join(" "):""}
|
|
1224
1225
|
) {
|
|
1225
1226
|
nodes {
|
|
1226
|
-
${
|
|
1227
|
+
${ct}
|
|
1227
1228
|
}
|
|
1228
1229
|
pageInfo {
|
|
1229
1230
|
endCursor
|
|
@@ -1231,7 +1232,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1231
1232
|
}
|
|
1232
1233
|
}
|
|
1233
1234
|
}
|
|
1234
|
-
}`,d=await
|
|
1235
|
+
}`,d=await P(this.config,{query:p,variables:{...l,after:t}},e),c=[],g=d.body.data?.project,m=$e(g||{id:"",fullPath:"",webUrl:""});return(g?.issues?.nodes||[]).forEach(I=>{c.push(mt(I,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.issues?.pageInfo??{endCursor:null,hasNextPage:!1},data:c.sort((I,L)=>(I.updatedDate||I.createdDate).getTime()-(L.updatedDate||L.createdDate).getTime())}}async getIssuesForRepos(s,e={}){let{cursor:t}=s||{},n=s.repoIds.map(g=>g.toString().startsWith(ne)?g:`${ne}${g}`),{variables:o,variableTypes:i,mergeRequestArguments:a}=this.getVariablesForPullRequests(s),u={projectIds:n,...o},l=`
|
|
1235
1236
|
query GetIssuesFromProject(
|
|
1236
1237
|
$projectIds: [ID!]
|
|
1237
1238
|
$after: String
|
|
@@ -1257,24 +1258,24 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1257
1258
|
${a.length?a.join(" "):""}
|
|
1258
1259
|
) {
|
|
1259
1260
|
nodes {
|
|
1260
|
-
${
|
|
1261
|
+
${ct}
|
|
1261
1262
|
}
|
|
1262
1263
|
}
|
|
1263
1264
|
}
|
|
1264
1265
|
}
|
|
1265
|
-
}`,p=await
|
|
1266
|
+
}`,p=await P(this.config,{query:l,variables:{...u,after:t}},e),d=[];return(p.body.data?.projects?.nodes||[]).forEach(g=>{if(!s.includeFromArchivedRepos&&g.archived)return;let m=$e(g);(g.issues?.nodes||[]).forEach(I=>d.push(mt(I,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:p.body?.data?.projects?.pageInfo??{endCursor:null,hasNextPage:!1},data:d.sort((g,m)=>(g.updatedDate||g.createdDate).getTime()-(m.updatedDate||m.createdDate).getTime())}}async setIssueState(s,e={}){let{issue:t,state:n}=s;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueState($fullPath: ID!, $issueId: String!, $status: IssueStateEvent!) {
|
|
1266
1267
|
updateIssue(input: { projectPath: $fullPath, iid: $issueId, stateEvent: $status }) {
|
|
1267
1268
|
issue {
|
|
1268
1269
|
id
|
|
1269
1270
|
}
|
|
1270
1271
|
}
|
|
1271
|
-
}`;if(!(await
|
|
1272
|
+
}`;if(!(await P(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,status:n==="OPEN"?"REOPEN":"CLOSE"}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue status")}async closeIssue(s,e={}){await this.setIssueState({...s,state:"CLOSED"},e)}async reOpenIssue(s,e={}){await this.setIssueState({...s,state:"OPEN"},e)}async setIssueLabels(s,e={}){let{issue:t,labels:n}=s;if(!t.repository)throw new Error('GitLab requires a "repository" for this function.');let o=n.map(u=>{if(!u.graphQLId)throw new Error('GitLab requires label "graphQLId" for this function.');return u.graphQLId}),i=`mutation SetIssueLabels($fullPath: ID!, $issueId: String!, $labelGraphQLIds: [ID!]) {
|
|
1272
1273
|
updateIssue(input: { projectPath: $fullPath, iid: $issueId, labelIds: $labelGraphQLIds }) {
|
|
1273
1274
|
issue {
|
|
1274
1275
|
id
|
|
1275
1276
|
}
|
|
1276
1277
|
}
|
|
1277
|
-
}`;if(!(await
|
|
1278
|
+
}`;if(!(await P(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,labelGraphQLIds:o}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue labels")}async setIssueMilestone(s,e={}){let{issue:t,milestone:n}=s;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueMilestone($fullPath: ID!, $issueId: String!, $milestoneId: ID) {
|
|
1278
1279
|
updateIssue(input: { projectPath: $fullPath, iid: $issueId, milestoneId: $milestoneId }) {
|
|
1279
1280
|
errors
|
|
1280
1281
|
issue {
|
|
@@ -1284,14 +1285,14 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1284
1285
|
}
|
|
1285
1286
|
}
|
|
1286
1287
|
}
|
|
1287
|
-
}`,i=await
|
|
1288
|
+
}`,i=await P(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,milestoneId:n?.id??null}},e),a=i.body.data?.updateIssue;if(!a?.issue?.id||i.body.errors||a?.errors?.length!==0)throw new Error("Could not set milestone of issue")}async setIssueAssignees(s,e={}){let{issue:t,assignees:n}=s;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=n.map(l=>l.username),i=`mutation SetIssueAssignees($fullPath: ID!, $issueId: String!, $assigneeUsernames: [String!]!) {
|
|
1288
1289
|
issueSetAssignees(input: { projectPath: $fullPath, iid: $issueId, assigneeUsernames: $assigneeUsernames }) {
|
|
1289
1290
|
errors,
|
|
1290
1291
|
issue {
|
|
1291
1292
|
id
|
|
1292
1293
|
}
|
|
1293
1294
|
}
|
|
1294
|
-
}`,u=(await
|
|
1295
|
+
}`,u=(await P(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,assigneeUsernames:o}},e)).body.data?.issueSetAssignees;if(!u?.issue?.id||u?.errors?.length!==0)throw new Error("Could not set issue assignees")}async getMilestonesForRepo(s,e={}){let{repo:{namespace:t,name:n},cursor:o}=s,i=await P(this.config,{query:`
|
|
1295
1296
|
query getLabelsForRepo(
|
|
1296
1297
|
$fullPath: ID!
|
|
1297
1298
|
$after: String
|
|
@@ -1302,7 +1303,7 @@ query getLabelsForRepo(
|
|
|
1302
1303
|
webUrl
|
|
1303
1304
|
milestones(after: $after) {
|
|
1304
1305
|
nodes {
|
|
1305
|
-
${
|
|
1306
|
+
${Rt}
|
|
1306
1307
|
}
|
|
1307
1308
|
pageInfo {
|
|
1308
1309
|
endCursor
|
|
@@ -1311,7 +1312,7 @@ query getLabelsForRepo(
|
|
|
1311
1312
|
}
|
|
1312
1313
|
}
|
|
1313
1314
|
}
|
|
1314
|
-
`,variables:{fullPath:`${t}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.milestones?.nodes?.map(a=>
|
|
1315
|
+
`,variables:{fullPath:`${t}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.milestones?.nodes?.map(a=>yt(a,i.body.data?.project?.webUrl||""))??[]}}async getLabelsForRepo(s,e={}){let{repo:{namespace:t,name:n},cursor:o}=s,i=await P(this.config,{query:`
|
|
1315
1316
|
query getLabelsForRepo(
|
|
1316
1317
|
$fullPath: ID!
|
|
1317
1318
|
$after: String
|
|
@@ -1321,7 +1322,7 @@ query getLabelsForRepo(
|
|
|
1321
1322
|
) {
|
|
1322
1323
|
labels(after: $after) {
|
|
1323
1324
|
nodes {
|
|
1324
|
-
${
|
|
1325
|
+
${It}
|
|
1325
1326
|
}
|
|
1326
1327
|
pageInfo {
|
|
1327
1328
|
endCursor
|
|
@@ -1330,8 +1331,8 @@ query getLabelsForRepo(
|
|
|
1330
1331
|
}
|
|
1331
1332
|
}
|
|
1332
1333
|
}
|
|
1333
|
-
`,variables:{fullPath:`${t}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(
|
|
1334
|
-
OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(L=>u.push(`labels = "${L}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,p=!o,d=p?sr:rr,c=new URL(`${z(r,t,o)}${d}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",De.toString()),c.searchParams.set("fields",It.join(",")),c.searchParams.set("expand","transitions"),n&&(p?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await r.request({url:c.toString(),headers:R(t.token||r.token)}),m=g.body.issues.map(L=>bt(L,a,e,o)),b=!1,I="";return p?(b=m.length==De,I=(parseInt(n??"0",10)+m.length).toString()):(b=!!g.body.nextPageToken,I=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:b,endCursor:I}}},nr=async(r,s,e,t={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=s||{},u=[...It],l=a?.Sprint;l&&u.push(l);let p=!o,d=p?sr:rr,c=new URL(`${z(r,t,o)}${d}`);c.searchParams.set("jql",i.join(" AND ")),c.searchParams.set("maxResults",De.toString()),c.searchParams.set("fields",u.join(",")),c.searchParams.set("expand","transitions"),n&&(p?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await r.request({url:c.toString(),headers:R(t.token||r.token)}),m=g.body.issues.map(L=>bt(L,a,e,o)),b=!1,I="";return p?(b=m.length==De,I=(parseInt(n??"0",10)+m.length).toString()):(b=!!g.body.nextPageToken,I=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:b,endCursor:I}}},Te=async(r,s,e,t={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:p,fields:d}=s||{},c=[`project = "${l}"`,"statusCategory != Done"];return o&&c.push(`creator in ("${o}")`),n&&n.length!==0&&c.push(`assignee in ("${n.join('", "')}")`),i&&c.push(`comment ~ "${i}"`),a&&a.forEach(g=>c.push(`labels = "${g}"`)),nr(r,{resourceId:p,jql:c,cursor:u,fields:d},e,t)},Oe=async(r,s,e,t={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:p,fields:d}=s||{},g=["("+l.map(m=>`project = "${m}"`).join(" OR ")+")","statusCategory != Done"];return o&&g.push(`creator in ("${o}")`),n&&n.length!==0&&g.push(`assignee in ("${n.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(m=>g.push(`labels = "${m}"`)),nr(r,{resourceId:p,jql:g,fields:d,cursor:u},e,t)},xe=async(r,s,e={})=>{let{issue:t,labels:n}=s;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:n.map(i=>i.name)}};await r.request({method:"PUT",url:`${z(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"}})},ke=async(r,s,e={})=>{let{issue:t,components:n}=s;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:n.map(i=>({id:i.id}))}};await r.request({method:"PUT",url:`${z(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"}})},Ne=async(r,s,e={})=>{let{issue:t,status:n}=s;if(!t.project)throw new Error('Jira requires a "project" for this function.');if(!n.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:n.id}};await r.request({method:"POST",url:`${z(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"}})},_e=async(r,s,e={})=>{let{resourceId:t,projectIdOrKey:n}=s,o=new URL(`${z(r,e,t)}/rest/api/2/project/${n}/components`);return{data:(await r.request({url:o.toString(),headers:R(e.token||r.token)})).body}};var le="https://api.atlassian.com/ex/jira",yt=100,re=class extends U{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,t={}){if(!this._issueFieldsCache[e.resourceId]){let n=await Ue(this.config,e,t);this._issueFieldsCache[e.resourceId]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,t={}){let n=t.token||this.config.token;if(!n)return null;let o=this._resourceUrlCache[n];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(t),this._resourceUrlCache[n]?.[e.resourceId]??null)}async getCurrentUserForResource(e,t={}){let n=await this.getResourceUrl({resourceId:e.resourceId},t),o=await this.config.request({url:`${t.baseUrl||le}/${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:n?`${n}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let t=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:R(e.token||this.config.token)}),n=e.token||this.config.token,o=n?this._resourceUrlCache[n]||{}:void 0,i=t.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return n&&(this._resourceUrlCache[n]=o),{data:i}}async getJiraProjectsForResource(e,t={}){let n=new URL(`${t.baseUrl||le}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",yt.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:n.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()},data:o.body.values.map(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,t={}){let n=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await $t(i=>this.getJiraProjectsForResource({resourceId:o,cursor:i},t))}catch{return[]}})).then((...o)=>{o.forEach(i=>{n=n.concat(...i)})}),{data:n}}async getAccountsForJiraProject(e,t={}){let{resourceId:n,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:n},t),u=new URL(`${t.baseUrl||le}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",yt.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()},data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>$e(p,a,!1))}}async getComponentsForJiraProject(e,t={}){return await _e(this.config,e,t)}async getIssue(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Ae(this.config,{...e,fields:n},o,t)}async getIssuesForProject(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Te(this.config,{...e,fields:n},o,t)}async getIssuesForProjects(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Oe(this.config,{...e,fields:n},o,t)}async getIssuesForResourceForCurrentUser(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Ge(this.config,{...e,fields:n},o,t)}async setIssueStatus(e,t={}){await Ne(this.config,e,t)}async setIssueAssignee(e,t={}){let{issue:n,assignee:o}=e;if(!n.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!n.project.resourceId)throw new Error('Jira Cloud requires a project "resourceId" for this function.');let i={accountId:o?.id};await this.config.request({method:"PUT",url:`${t.baseUrl||le}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(i),headers:{...R(t.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,t={}){await ke(this.config,e,t)}async setIssueLabels(e,t={}){await xe(this.config,e,t)}async getLabelsForResource(e,t={}){let{resourceId:n,cursor:o}=e,i=new URL(`${t.baseUrl||le}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",yt.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 se=class extends D{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let t=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[t]){let n=await Ue(this.config,{},e);this._issueFieldsCache[t]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[t]??null}async getCurrentUser(e={}){let t=await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/myself`,headers: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(n=>({id:n.id,name:n.name}))}}async getIssue(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Ae(this.config,{...e,fields:o},n,t)}async getIssuesForProject(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Te(this.config,{...e,fields:o},n,t)}async getIssuesForProjects(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Oe(this.config,{...e,fields:o},n,t)}async getIssuesForResourceForCurrentUser(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Ge(this.config,{...e,fields:o},n,t)}async setIssueStatus(e,t={}){await Ne(this.config,e,t)}async setIssueLabels(e,t={}){await xe(this.config,e,t)}async setIssueComponents(e,t={}){await ke(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:n})=>({color:null,description:null,id:null,name:n}))}}async getComponentsForJiraProject(e,t={}){return await _e(this.config,e,t)}};var O="https://api.trello.com",_s=1e3,x=(r,s)=>({...R(s),Authorization:`OAuth oauth_consumer_key="${r}", oauth_token="${s}"`}),Fs=r=>({id:r.id,username:r.username,url:r.url,name:r.fullName,email:r.email,avatarUrl:r.avatarUrl}),Qs=(r,s)=>{let e=new Date(1e3*parseInt(r.id.substring(0,8),16));return{id:r.id,commentCount:r.badges.comments,number:r.idShort.toString(),title:r.name,url:r.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(r.dateLastActivity),assignees:r.members.map(t=>({id:t.id,username:t.username,name:t.fullName,email:null,avatarUrl:t.avatarUrl,url:null})),description:null,state:s[r.idList??""]?{id:r.idList,name:s[r.idList].name,color:null}:null,type:null,repository:null,upvoteCount:r.badges.votes,labels:r.labels.map(t=>({color:t.color,description:null,id:t.id,name:t.name}))}},ne=class extends U{async getCurrentUser(s,e={}){let t=await this.config.request({url:`${e.baseUrl||O}/1/members/me`,headers:x(s.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(s,e={}){return{data:(await this.config.request({url:`${e.baseUrl||O}/1/members/me/boards?fields=name&filter=open`,headers:x(s.appKey,e.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getListsForTrelloBoard(s,e={}){let{appKey:t,boardId:n}=s;return{data:(await this.config.request({url:`${e.baseUrl||O}/1/boards/${n}/lists`,headers:x(t,e.token||this.config.token)})).body}}async getAccountForId(s,e={}){let{appKey:t,memberId:n}=s,o=await this.config.request({url:`${e.baseUrl||O}/1/members/${n}`,headers:x(t,e.token||this.config.token)});return{data:Fs(o.body)}}async getAccountsForTrelloBoard(s,e={}){let{appKey:t,boardId:n}=s;return{data:(await this.config.request({url:`${e.baseUrl||O}/1/boards/${n}/members`,headers:x(t,e.token||this.config.token)})).body.map(i=>({id:i.id,name:i.fullName,username:i.username,email:null,avatarUrl:null,url:null}))}}async getIssuesForBoard(s,e={}){let t=["-is:archived","sort:edited"],{appKey:n,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=s||{};a&&t.push("@me"),u&&u.forEach(c=>t.push(`label:"${c}"`));let p=`${i?`${i}`:""}${t.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||O}/1/search?query=${p}&cards_limit=${_s}&card_members=true`,headers:x(n,e.token||this.config.token)})).body.cards.map(c=>Qs(c,l||{}))}}async updateIssue(s,e,t,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||O}/1/cards/${e.id}?${t}`,headers:x(s,n.token||this.config.token)})}async setIssueStatus(s,e={}){let{appKey:t,issue:n,status:o}=s;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(t,n,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(s,e={}){let{appKey:t,issue:n,assignees:o}=s,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(t,n,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(s,e={}){let{appKey:t,issue:n,labels:o}=s,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||O}/1/cards/${n.id}?idLabels=${encodeURIComponent(i)}`,headers:x(t,e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(s,e={}){let{appKey:t,issue:n,archived:o}=s;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||O}/1/cards/${n.id}?closed=${o}`,headers:x(t,e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(s,e={}){await this.setIssueArchived({...s,archived:!0},e)}async unArchiveIssue(s,e={}){await this.setIssueArchived({...s,archived:!1},e)}async getLabelsForBoard(s,e={}){let{appKey:t,boardId:n}=s;return{data:(await this.config.request({url:`${e.baseUrl||O}/1/boards/${n}/labels`,headers:x(t,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var wt=100,Fe=class{constructor(){this.set=new Set;this.arr=[]}push(...s){let e=s.filter(t=>!this.set.has(t.id));this.arr.push(...e),e.forEach(t=>this.set.add(t.id))}get length(){return this.arr.length}get items(){return this.arr}},F=async(r,s,e,t)=>{let n=s.token||r.token;if(!n)throw new Error("Linear API key is required");let o=await r.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:n,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:t})});if(o.status>=400)throw new Error(`Linear API request failed: ${o.status} ${o.statusText}`);let i=o.body;if(i.errors)throw new Error(`Linear GraphQL errors: ${i.errors.map(a=>a.message).join(", ")}`);return i.data},Pt=r=>r?r instanceof Date?r:new Date(r):null,js=`
|
|
1334
|
+
`,variables:{fullPath:`${t}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(bt)??[]}}async getTreeForRepo(s,e={}){let t=H(s.repo),n=new URL(s.cursor??`${Le(this.config,e)}/projects/${encodeURIComponent(t)}/repository/tree`);n.searchParams.set("per_page","10000"),n.searchParams.set("recursive","true"),n.searchParams.set("pagination","keyset"),n.searchParams.set("ref",s.branch);let o=await this.config.request({url:n.toString(),headers:R(e.token||this.config.token)}),i=o.headers.link;return{data:o.body.map(Ns),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}};var js="https://api.atlassian.com/ex/jira",Ue=100,Pt=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],ur="/rest/api/2/search/jql",lr="/rest/api/2/search",wt=(r,s,e,t)=>{let n=r.fields.assignee,o=!t,i=(r.fields[s?.Sprint??""]??[]).filter(a=>typeof a=="object");return{id:r.id,commentCount:r.fields.comment.comments.length,number:r.key,title:r.fields.summary,url:e?`${e}/browse/${r.key}`:null,closedDate:null,createdDate:new Date(r.fields.created),author:Ae(r.fields.creator,e,o),updatedDate:new Date(r.fields.updated),assignees:n?[Ae(n,e,o)]:[],description:r.fields.description,repository:null,project:{name:r.fields.project.name,resourceId:t??null,key:r.fields.project.key,namespace:null,id:r.fields.project.id},state:Hs(r.fields.status),statusTransitions:r.transitions?.map(Bs)??[],components:r.fields.components?.map(Ms)??[],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(Ws),fixVersions:r.fields.fixVersions.map(Js)}},Bs=r=>{let s;switch(r.to.statusCategory.name){case"To Do":s="TO_DO";break;case"In Progress":s="IN_PROGRESS";break;default:s="DONE";break}return{name:r.name,id:r.id,to:{id:r.to.id,name:r.to.name,color:r.to.statusCategory.colorName,category:s}}},Ms=r=>({description:r.description??null,id:r.id,name:r.name}),zs=(r,s,e)=>e&&r.name?`${s}/secure/ViewProfile.jspa?name=${encodeURIComponent(r.name)}`:`${s}/jira/people/${r.accountId}`,Ae=(r,s,e)=>({id:(e?r.key:r.accountId)??"",name:r.displayName,email:r.emailAddress,avatarUrl:r.avatarUrls["48x48"],username:r.displayName,url:zs(r,s,e)}),Hs=r=>{let s;switch(r.statusCategory.name){case"To Do":s="TO_DO";break;case"In Progress":s="IN_PROGRESS";break;default:s="DONE";break}return{id:r.id,name:r.name,color:r.statusCategory.colorName,category:s}},Ws=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}),Js=r=>({id:r.id,description:r.description,name:r.name,archived:r.archived,released:r.released,releaseDate:r.releaseDate?new Date(r.releaseDate):null}),W=(r,s,e)=>e?`${s.baseUrl||js}/${e}`:`${s?.baseUrl||r.baseUrl}`,Ge=async(r,s,e={})=>{let{resourceId:t}=s;return(await r.request({url:`${W(r,e,t)}/rest/api/2/field`,headers:R(e.token||r.token)})).body},Te=async(r,s,e,t={})=>{let{number:n,resourceId:o,fields:i}=s||{},a=await r.request({url:`${W(r,t,o)}/rest/api/2/issue/${n}?fields=${Pt.join(",")}&expand=transitions`,headers:R(t.token||r.token)});return{data:wt(a.body,i,e,o)}},Oe=async(r,s,e,t={})=>{let{cursor:n,resourceId:o,labelNames:i,fields:a}=s||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
|
|
1335
|
+
OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(L=>u.push(`labels = "${L}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,p=!o,d=p?lr:ur,c=new URL(`${W(r,t,o)}${d}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",Ue.toString()),c.searchParams.set("fields",Pt.join(",")),c.searchParams.set("expand","transitions"),n&&(p?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await r.request({url:c.toString(),headers:R(t.token||r.token)}),m=g.body.issues.map(L=>wt(L,a,e,o)),b=!1,I="";return p?(b=m.length==Ue,I=(parseInt(n??"0",10)+m.length).toString()):(b=!!g.body.nextPageToken,I=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:b,endCursor:I}}},pr=async(r,s,e,t={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=s||{},u=[...Pt],l=a?.Sprint;l&&u.push(l);let p=!o,d=p?lr:ur,c=new URL(`${W(r,t,o)}${d}`);c.searchParams.set("jql",i.join(" AND ")),c.searchParams.set("maxResults",Ue.toString()),c.searchParams.set("fields",u.join(",")),c.searchParams.set("expand","transitions"),n&&(p?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await r.request({url:c.toString(),headers:R(t.token||r.token)}),m=g.body.issues.map(L=>wt(L,a,e,o)),b=!1,I="";return p?(b=m.length==Ue,I=(parseInt(n??"0",10)+m.length).toString()):(b=!!g.body.nextPageToken,I=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:b,endCursor:I}}},xe=async(r,s,e,t={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:p,fields:d}=s||{},c=[`project = "${l}"`,"statusCategory != Done"];return o&&c.push(`creator in ("${o}")`),n&&n.length!==0&&c.push(`assignee in ("${n.join('", "')}")`),i&&c.push(`comment ~ "${i}"`),a&&a.forEach(g=>c.push(`labels = "${g}"`)),pr(r,{resourceId:p,jql:c,cursor:u,fields:d},e,t)},ke=async(r,s,e,t={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:p,fields:d}=s||{},g=["("+l.map(m=>`project = "${m}"`).join(" OR ")+")","statusCategory != Done"];return o&&g.push(`creator in ("${o}")`),n&&n.length!==0&&g.push(`assignee in ("${n.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(m=>g.push(`labels = "${m}"`)),pr(r,{resourceId:p,jql:g,fields:d,cursor:u},e,t)},Ne=async(r,s,e={})=>{let{issue:t,labels:n}=s;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:n.map(i=>i.name)}};await r.request({method:"PUT",url:`${W(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"}})},_e=async(r,s,e={})=>{let{issue:t,components:n}=s;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:n.map(i=>({id:i.id}))}};await r.request({method:"PUT",url:`${W(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"}})},Fe=async(r,s,e={})=>{let{issue:t,status:n}=s;if(!t.project)throw new Error('Jira requires a "project" for this function.');if(!n.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:n.id}};await r.request({method:"POST",url:`${W(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"}})},Qe=async(r,s,e={})=>{let{resourceId:t,projectIdOrKey:n}=s,o=new URL(`${W(r,e,t)}/rest/api/2/project/${n}/components`);return{data:(await r.request({url:o.toString(),headers:R(e.token||r.token)})).body}};var ce="https://api.atlassian.com/ex/jira",St=100,ie=class extends G{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,t={}){if(!this._issueFieldsCache[e.resourceId]){let n=await Ge(this.config,e,t);this._issueFieldsCache[e.resourceId]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,t={}){let n=t.token||this.config.token;if(!n)return null;let o=this._resourceUrlCache[n];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(t),this._resourceUrlCache[n]?.[e.resourceId]??null)}async getCurrentUserForResource(e,t={}){let n=await this.getResourceUrl({resourceId:e.resourceId},t),o=await this.config.request({url:`${t.baseUrl||ce}/${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:n?`${n}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let t=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:R(e.token||this.config.token)}),n=e.token||this.config.token,o=n?this._resourceUrlCache[n]||{}:void 0,i=t.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return n&&(this._resourceUrlCache[n]=o),{data:i}}async getJiraProjectsForResource(e,t={}){let n=new URL(`${t.baseUrl||ce}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",St.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:n.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()},data:o.body.values.map(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,t={}){let n=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await Ot(i=>this.getJiraProjectsForResource({resourceId:o,cursor:i},t))}catch{return[]}})).then((...o)=>{o.forEach(i=>{n=n.concat(...i)})}),{data:n}}async getAccountsForJiraProject(e,t={}){let{resourceId:n,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:n},t),u=new URL(`${t.baseUrl||ce}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",St.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()},data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>Ae(p,a,!1))}}async getComponentsForJiraProject(e,t={}){return await Qe(this.config,e,t)}async getIssue(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Te(this.config,{...e,fields:n},o,t)}async getIssuesForProject(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await xe(this.config,{...e,fields:n},o,t)}async getIssuesForProjects(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await ke(this.config,{...e,fields:n},o,t)}async getIssuesForResourceForCurrentUser(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Oe(this.config,{...e,fields:n},o,t)}async setIssueStatus(e,t={}){await Fe(this.config,e,t)}async setIssueAssignee(e,t={}){let{issue:n,assignee:o}=e;if(!n.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!n.project.resourceId)throw new Error('Jira Cloud requires a project "resourceId" for this function.');let i={accountId:o?.id};await this.config.request({method:"PUT",url:`${t.baseUrl||ce}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(i),headers:{...R(t.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,t={}){await _e(this.config,e,t)}async setIssueLabels(e,t={}){await Ne(this.config,e,t)}async getLabelsForResource(e,t={}){let{resourceId:n,cursor:o}=e,i=new URL(`${t.baseUrl||ce}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",St.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 ae=class extends ${constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let t=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[t]){let n=await Ge(this.config,{},e);this._issueFieldsCache[t]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[t]??null}async getCurrentUser(e={}){let t=await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/myself`,headers: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(n=>({id:n.id,name:n.name}))}}async getIssue(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Te(this.config,{...e,fields:o},n,t)}async getIssuesForProject(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await xe(this.config,{...e,fields:o},n,t)}async getIssuesForProjects(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await ke(this.config,{...e,fields:o},n,t)}async getIssuesForResourceForCurrentUser(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Oe(this.config,{...e,fields:o},n,t)}async setIssueStatus(e,t={}){await Fe(this.config,e,t)}async setIssueLabels(e,t={}){await Ne(this.config,e,t)}async setIssueComponents(e,t={}){await _e(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:n})=>({color:null,description:null,id:null,name:n}))}}async getComponentsForJiraProject(e,t={}){return await Qe(this.config,e,t)}};var k="https://api.trello.com",Vs=1e3,N=(r,s)=>({...R(s),Authorization:`OAuth oauth_consumer_key="${r}", oauth_token="${s}"`}),Ks=r=>({id:r.id,username:r.username,url:r.url,name:r.fullName,email:r.email,avatarUrl:r.avatarUrl}),Xs=(r,s)=>{let e=new Date(1e3*parseInt(r.id.substring(0,8),16));return{id:r.id,commentCount:r.badges.comments,number:r.idShort.toString(),title:r.name,url:r.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(r.dateLastActivity),assignees:r.members.map(t=>({id:t.id,username:t.username,name:t.fullName,email:null,avatarUrl:t.avatarUrl,url:null})),description:null,state:s[r.idList??""]?{id:r.idList,name:s[r.idList].name,color:null}:null,type:null,repository:null,upvoteCount:r.badges.votes,labels:r.labels.map(t=>({color:t.color,description:null,id:t.id,name:t.name}))}},ue=class extends G{async getCurrentUser(s,e={}){let t=await this.config.request({url:`${e.baseUrl||k}/1/members/me`,headers:N(s.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(s,e={}){return{data:(await this.config.request({url:`${e.baseUrl||k}/1/members/me/boards?fields=name&filter=open`,headers:N(s.appKey,e.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getListsForTrelloBoard(s,e={}){let{appKey:t,boardId:n}=s;return{data:(await this.config.request({url:`${e.baseUrl||k}/1/boards/${n}/lists`,headers:N(t,e.token||this.config.token)})).body}}async getAccountForId(s,e={}){let{appKey:t,memberId:n}=s,o=await this.config.request({url:`${e.baseUrl||k}/1/members/${n}`,headers:N(t,e.token||this.config.token)});return{data:Ks(o.body)}}async getAccountsForTrelloBoard(s,e={}){let{appKey:t,boardId:n}=s;return{data:(await this.config.request({url:`${e.baseUrl||k}/1/boards/${n}/members`,headers:N(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(s,e={}){let t=["-is:archived","sort:edited"],{appKey:n,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=s||{};a&&t.push("@me"),u&&u.forEach(c=>t.push(`label:"${c}"`));let p=`${i?`${i}`:""}${t.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||k}/1/search?query=${p}&cards_limit=${Vs}&card_members=true`,headers:N(n,e.token||this.config.token)})).body.cards.map(c=>Xs(c,l||{}))}}async updateIssue(s,e,t,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||k}/1/cards/${e.id}?${t}`,headers:N(s,n.token||this.config.token)})}async setIssueStatus(s,e={}){let{appKey:t,issue:n,status:o}=s;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(t,n,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(s,e={}){let{appKey:t,issue:n,assignees:o}=s,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(t,n,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(s,e={}){let{appKey:t,issue:n,labels:o}=s,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||k}/1/cards/${n.id}?idLabels=${encodeURIComponent(i)}`,headers:N(t,e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(s,e={}){let{appKey:t,issue:n,archived:o}=s;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||k}/1/cards/${n.id}?closed=${o}`,headers:N(t,e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(s,e={}){await this.setIssueArchived({...s,archived:!0},e)}async unArchiveIssue(s,e={}){await this.setIssueArchived({...s,archived:!1},e)}async getLabelsForBoard(s,e={}){let{appKey:t,boardId:n}=s;return{data:(await this.config.request({url:`${e.baseUrl||k}/1/boards/${n}/labels`,headers:N(t,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var qt=100,je=class{constructor(){this.set=new Set;this.arr=[]}push(...s){let e=s.filter(t=>!this.set.has(t.id));this.arr.push(...e),e.forEach(t=>this.set.add(t.id))}get length(){return this.arr.length}get items(){return this.arr}},B=async(r,s,e,t)=>{let n=s.token||r.token;if(!n)throw new Error("Linear API key is required");let o=await r.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:n,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:t})});if(o.status>=400)throw new Error(`Linear API request failed: ${o.status} ${o.statusText}`);let i=o.body;if(i.errors)throw new Error(`Linear GraphQL errors: ${i.errors.map(a=>a.message).join(", ")}`);return i.data},vt=r=>r?r instanceof Date?r:new Date(r):null,Zs=`
|
|
1335
1336
|
id
|
|
1336
1337
|
name
|
|
1337
1338
|
description
|
|
@@ -1339,11 +1340,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1339
1340
|
startDate
|
|
1340
1341
|
targetDate
|
|
1341
1342
|
url
|
|
1342
|
-
`,
|
|
1343
|
+
`,dr=r=>({id:r.id,name:r.name,description:r.description??null,state:r.state,startDate:vt(r.startDate),targetDate:vt(r.targetDate),url:r.url}),cr=async(r,s,e)=>{let t=`
|
|
1343
1344
|
query GetProjects($first: Int!, $after: String) {
|
|
1344
1345
|
projects(first: $first, after: $after) {
|
|
1345
1346
|
nodes {
|
|
1346
|
-
${
|
|
1347
|
+
${Zs}
|
|
1347
1348
|
}
|
|
1348
1349
|
pageInfo {
|
|
1349
1350
|
hasNextPage
|
|
@@ -1351,7 +1352,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1351
1352
|
}
|
|
1352
1353
|
}
|
|
1353
1354
|
}
|
|
1354
|
-
`;return(await
|
|
1355
|
+
`;return(await B(r,s,t,{first:qt,after:e})).projects},Ys=`
|
|
1355
1356
|
id
|
|
1356
1357
|
name
|
|
1357
1358
|
number
|
|
@@ -1359,11 +1360,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1359
1360
|
startsAt
|
|
1360
1361
|
endsAt
|
|
1361
1362
|
completedAt
|
|
1362
|
-
`,
|
|
1363
|
+
`,gr=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:vt(r.completedAt),url:""}),mr=async(r,s,e)=>{let t=`
|
|
1363
1364
|
query GetCycles($first: Int!, $after: String) {
|
|
1364
1365
|
cycles(first: $first, after: $after) {
|
|
1365
1366
|
nodes {
|
|
1366
|
-
${
|
|
1367
|
+
${Ys}
|
|
1367
1368
|
}
|
|
1368
1369
|
pageInfo {
|
|
1369
1370
|
hasNextPage
|
|
@@ -1371,16 +1372,16 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1371
1372
|
}
|
|
1372
1373
|
}
|
|
1373
1374
|
}
|
|
1374
|
-
`;return(await
|
|
1375
|
+
`;return(await B(r,s,t,{first:qt,after:e})).cycles},en=`
|
|
1375
1376
|
id
|
|
1376
1377
|
name
|
|
1377
1378
|
color
|
|
1378
1379
|
description
|
|
1379
|
-
`,
|
|
1380
|
+
`,hr=r=>({id:r.id,name:r.name,color:r.color,description:r.description??null}),fr=async(r,s,e)=>{let t=`
|
|
1380
1381
|
query GetLabels($first: Int!, $after: String) {
|
|
1381
1382
|
projectLabels(first: $first, after: $after) {
|
|
1382
1383
|
nodes {
|
|
1383
|
-
${
|
|
1384
|
+
${en}
|
|
1384
1385
|
}
|
|
1385
1386
|
pageInfo {
|
|
1386
1387
|
hasNextPage
|
|
@@ -1388,36 +1389,36 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1388
1389
|
}
|
|
1389
1390
|
}
|
|
1390
1391
|
}
|
|
1391
|
-
`;return(await
|
|
1392
|
+
`;return(await B(r,s,t,{first:qt,after:e})).projectLabels};var ge=(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))(ge||{});function Rr(r,s){return r?`${ge[r]}:${s||""}`:s??null}function Ir(r){if(!r)return{category:0};let[s,e]=r.split(":");return s in ge?{category:ge[s],cursor:e||void 0}:{category:0,cursor:r}}var br=100;function Me(r){return r?r instanceof Date?r:new Date(r):null}var wr=`
|
|
1392
1393
|
id
|
|
1393
1394
|
name
|
|
1394
1395
|
key
|
|
1395
1396
|
icon
|
|
1396
|
-
`;function
|
|
1397
|
+
`;function tn(r){return{id:r.id,name:r.name,key:r.key,iconUrl:r.icon}}var yr=`
|
|
1397
1398
|
id
|
|
1398
1399
|
name
|
|
1399
1400
|
avatarUrl
|
|
1400
|
-
`;function
|
|
1401
|
+
`;function Pr(r){return r?{id:r.id,name:r.name,username:r.name,email:null,avatarUrl:r.avatarUrl??null,url:null}:null}var rn=`
|
|
1401
1402
|
id
|
|
1402
1403
|
name
|
|
1403
|
-
`;function
|
|
1404
|
+
`;function sn(r,s){if(r)return{id:r.id,name:r.name,key:s?.key||null,namespace:null,resourceId:s?.id||null}}var nn=`
|
|
1404
1405
|
id
|
|
1405
1406
|
sortOrder
|
|
1406
1407
|
name
|
|
1407
1408
|
description
|
|
1408
1409
|
status
|
|
1409
1410
|
targetDate
|
|
1410
|
-
`;function
|
|
1411
|
+
`;function on(r){return r?{id:r.id,number:r.sortOrder,title:r.name,description:r.description??null,isOpen:r.status!=="done",url:"",startDate:null,dueDate:Me(r.targetDate)}:null}function an(r){switch(r){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var un=`
|
|
1411
1412
|
id
|
|
1412
1413
|
name
|
|
1413
1414
|
color
|
|
1414
1415
|
type
|
|
1415
|
-
`;function
|
|
1416
|
+
`;function ln(r){return r?{id:r.id,name:r.name,color:r.color,category:an(r.type)}:null}var Ct=`
|
|
1416
1417
|
creator {
|
|
1417
|
-
${
|
|
1418
|
+
${yr}
|
|
1418
1419
|
}
|
|
1419
1420
|
assignee {
|
|
1420
|
-
${
|
|
1421
|
+
${yr}
|
|
1421
1422
|
}
|
|
1422
1423
|
archivedAt
|
|
1423
1424
|
createdAt
|
|
@@ -1425,35 +1426,35 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1425
1426
|
id
|
|
1426
1427
|
identifier
|
|
1427
1428
|
project {
|
|
1428
|
-
${
|
|
1429
|
+
${rn}
|
|
1429
1430
|
}
|
|
1430
1431
|
team {
|
|
1431
|
-
${
|
|
1432
|
+
${wr}
|
|
1432
1433
|
}
|
|
1433
1434
|
state {
|
|
1434
|
-
${
|
|
1435
|
+
${un}
|
|
1435
1436
|
}
|
|
1436
1437
|
title
|
|
1437
1438
|
updatedAt
|
|
1438
1439
|
url
|
|
1439
1440
|
projectMilestone {
|
|
1440
|
-
${
|
|
1441
|
+
${nn}
|
|
1441
1442
|
}
|
|
1442
|
-
`;async function
|
|
1443
|
+
`;async function Et(r){return{author:Pr(await r.creator),assignees:[Pr(await r.assignee)].filter(s=>s!=null),commentCount:null,closedDate:Me(r.archivedAt),createdDate:Me(r.createdAt),description:r.description??null,id:r.id,labels:[],number:r.identifier,repository:null,project:sn(await r.project,await r.team),state:ln(await r.state),title:r.title,type:null,updatedDate:Me(r.updatedAt),upvoteCount:null,url:r.url,milestone:on(await r.projectMilestone)}}var Be=`
|
|
1443
1444
|
nodes {
|
|
1444
|
-
${
|
|
1445
|
+
${Ct}
|
|
1445
1446
|
}
|
|
1446
1447
|
pageInfo {
|
|
1447
1448
|
hasNextPage
|
|
1448
1449
|
endCursor
|
|
1449
1450
|
}
|
|
1450
|
-
`,
|
|
1451
|
+
`,ze=class extends G{async fetchIssue(s,e){let t=`
|
|
1451
1452
|
query GetIssue($identifier: String!) {
|
|
1452
1453
|
issue(id: $identifier) {
|
|
1453
|
-
${
|
|
1454
|
+
${Ct}
|
|
1454
1455
|
}
|
|
1455
1456
|
}
|
|
1456
|
-
`;return(await
|
|
1457
|
+
`;return(await B(this.config,e,t,{identifier:s})).issue}async fetchOrganization(s){let e=`
|
|
1457
1458
|
query GetOrganization {
|
|
1458
1459
|
organization {
|
|
1459
1460
|
id
|
|
@@ -1461,15 +1462,15 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1461
1462
|
urlKey
|
|
1462
1463
|
}
|
|
1463
1464
|
}
|
|
1464
|
-
`;return(await
|
|
1465
|
+
`;return(await B(this.config,s,e)).organization}async fetchTeams(s){let e=`
|
|
1465
1466
|
query GetTeams {
|
|
1466
1467
|
teams {
|
|
1467
1468
|
nodes {
|
|
1468
|
-
${
|
|
1469
|
+
${wr}
|
|
1469
1470
|
}
|
|
1470
1471
|
}
|
|
1471
1472
|
}
|
|
1472
|
-
`;return(await
|
|
1473
|
+
`;return(await B(this.config,s,e)).teams}async rawRequest(s,e,t){return{data:await B(this.config,s,e,t)}}async fetchViewer(s){let e=`
|
|
1473
1474
|
query GetViewer {
|
|
1474
1475
|
viewer {
|
|
1475
1476
|
id
|
|
@@ -1478,11 +1479,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1478
1479
|
displayName
|
|
1479
1480
|
}
|
|
1480
1481
|
}
|
|
1481
|
-
`;return(await
|
|
1482
|
+
`;return(await B(this.config,s,e)).viewer}async getIssue(s,e={}){let t=await this.fetchIssue(s.number,e);return{data:await Et(t)}}async getLinearOrganization(s={}){let e=await this.fetchOrganization(s);return{data:{id:e.id,name:e.name,key:e.urlKey,url:`https://linear.app/${e.urlKey}`}}}async getTeamsForCurrentUser(s={}){return{data:(await this.fetchTeams(s)).nodes.map(tn)}}async getProjects(s={},e={}){let t=await cr(this.config,e,s.cursor??void 0);return{data:t.nodes.map(dr),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getCycles(s={},e={}){let t=await mr(this.config,e,s.cursor??void 0);return{data:t.nodes.map(gr),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getLabels(s={},e={}){let t=await fr(this.config,e,s.cursor??void 0);return{data:t.nodes.map(hr),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getCurrentUser(s={}){return{data:await this.fetchViewer(s)}}async getIssuesForCurrentUser(s,e={}){let{cursor:t}=s,{category:n,cursor:o}=Ir(t),i=await this.fetchViewer(e),a,u,l=new je,p=async(d,c)=>{if(u||n>d)return;let g=await c(Math.max(br-l.length,1),n===d?o:void 0);if(!g)return;let m=await Ke(g.nodes.map(Et));l.push(...m),g.pageInfo.hasNextPage&&(a=d,u=g.pageInfo.endCursor)};return await p(1,async(d,c)=>(await this.rawRequest(e,`
|
|
1482
1483
|
query GetAssignedIssues($first: Int!, $after: String) {
|
|
1483
1484
|
viewer {
|
|
1484
1485
|
issues: assignedIssues(first: $first, after: $after) {
|
|
1485
|
-
${
|
|
1486
|
+
${Be}
|
|
1486
1487
|
}
|
|
1487
1488
|
}
|
|
1488
1489
|
}
|
|
@@ -1490,7 +1491,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1490
1491
|
query GetCreatedIssues($first: Int!, $after: String) {
|
|
1491
1492
|
viewer {
|
|
1492
1493
|
issues: createdIssues(first: $first, after: $after) {
|
|
1493
|
-
${
|
|
1494
|
+
${Be}
|
|
1494
1495
|
}
|
|
1495
1496
|
}
|
|
1496
1497
|
}
|
|
@@ -1515,7 +1516,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1515
1516
|
}]
|
|
1516
1517
|
}
|
|
1517
1518
|
){
|
|
1518
|
-
${
|
|
1519
|
+
${Be}
|
|
1519
1520
|
}
|
|
1520
1521
|
}
|
|
1521
1522
|
`,{first:d,after:c})).data?.issues),await p(5,async(d,c)=>{let m=(await this.rawRequest(e,`
|
|
@@ -1541,7 +1542,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1541
1542
|
){
|
|
1542
1543
|
nodes {
|
|
1543
1544
|
issue {
|
|
1544
|
-
${
|
|
1545
|
+
${Ct}
|
|
1545
1546
|
}
|
|
1546
1547
|
}
|
|
1547
1548
|
pageInfo {
|
|
@@ -1550,10 +1551,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1550
1551
|
}
|
|
1551
1552
|
}
|
|
1552
1553
|
}
|
|
1553
|
-
`,{first:d,after:c})).data?.comments;return m?{nodes:m.nodes.map(I=>I.issue),pageInfo:m.pageInfo}:void 0}),{data:l.items,pageInfo:{hasNextPage:!!u,endCursor:
|
|
1554
|
+
`,{first:d,after:c})).data?.comments;return m?{nodes:m.nodes.map(I=>I.issue),pageInfo:m.pageInfo}:void 0}),{data:l.items,pageInfo:{hasNextPage:!!u,endCursor:Rr(a,u)}}}async getIssues(s,e={}){let{teams:t,projects:n,labels:o,cursor:i}=s,a=[];if(t&&t.length>0){let g=t.map(m=>`"${m}"`).join(", ");a.push(`team: { id: { in: [${g}] } }`)}if(n&&n.length>0){let g=n.map(m=>`"${m}"`).join(", ");a.push(`project: { id: { in: [${g}] } }`)}if(o&&o.length>0){let g=o.map(m=>`"${m}"`).join(", ");a.push(`labels: { name: { in: [${g}] } }`)}let u=a.length>0?`filter: { ${a.join(", ")} }`:"",l=`
|
|
1554
1555
|
query GetIssues($first: Int!, $after: String) {
|
|
1555
1556
|
issues(first: $first, after: $after${u?", ":""}${u}) {
|
|
1556
|
-
${
|
|
1557
|
+
${Be}
|
|
1557
1558
|
}
|
|
1558
1559
|
}
|
|
1559
|
-
`,d=(await this.rawRequest(e,l,{first:
|
|
1560
|
+
`,d=(await this.rawRequest(e,l,{first:br,after:i})).data?.issues;return d?{data:await Ke(d.nodes.map(Et)),pageInfo:{hasNextPage:d.pageInfo.hasNextPage,endCursor:d.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var Sr=r=>{let s={request:r?.request};return{azureDevOps:new ee({...s,...r?.azureDevOps}),bitbucket:new te({...s,...r?.bitbucket}),bitbucketServer:new re({...s,...r?.bitbucketServer}),github:new se({...s,...r?.github}),gitlab:new oe({...s,...r?.gitlab}),jira:new ie({...s,...r?.jira}),jiraServer:new ae({...s,...r?.jiraServer}),linear:new ze({...s,...r?.linear}),trello:new ue({...s,...r?.trello})}};var vr=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(vr||{});var qr=(e=>(e.Zero="0",e.One="1",e))(qr||{}),Er=(e=>(e.PullRequest="pr",e.Issue="issue",e))(Er||{}),Cr=(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))(Cr||{});var Lr=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(Lr||{});var pn=Sr;
|