@gitkraken/integrations-tools
Runtime-agnostic GitKraken integration primitives:
- Remote resolution:
parseRemoteUrlturns a git remote URL into the provider, owner and repository the provider APIs need. - Provider tokens:
getProviderToken/refreshProviderTokenfetch and rotate a git provider connection's token from the GitKraken API. - Provider connections:
getAuthorizeUrl,savePat,deleteProviderToken,getConnectionToken,refreshConnectionToken,deleteConnectionandsetPrimaryConnectionmanage a provider's connections (several per provider included) through the GitKraken API. - Token verification:
verifyProviderTokenandgetProviderAccountNameprobe a token against the provider. - Directory listings:
listProviderOrganizations,listProviderProjectsandlistProviderRepositorieslist what a connection can see, with warnings for partial results. - Pull-request search:
searchPullRequestslists the pull requests a connection's user authored, is assigned or is asked to review, on every git host. - Issues:
searchIssues,getIssue,assignIssueandvalidateIssueCriteriacover GitHub, GitLab, Jira, Azure DevOps, Linear and Trello. - Pull-request targets:
resolvePullRequestTargetandopenPullRequestcover a host's whole "open a PR for this remote" flow: provider detection, the cloud-token/local-token fallback, the self-hosted host check, and one refresh and retry on a rejected OAuth token. - Pull-request creation:
createPullRequestopens a pull request (a merge request on GitLab) on GitHub, GitHub Enterprise, GitLab, self-hosted GitLab, Bitbucket, Bitbucket Server, Azure DevOps and Azure DevOps Server. - Pull-request detail:
getPullRequest,getPullRequestCommentsandcreatePullRequestReviewread a pull request (with its changed files), read its comments and submit a review or approval on every git host. - File content:
getFileContentreads a repository file at a branch, tag or commit on every git host. - Issue writes:
createIssueandaddIssueCommentopen an issue and comment on one for GitHub, GitLab, Jira, Azure DevOps and Linear (Trello cannot create issues). - Launchpad prioritization: the priority-model tables and pure grouping/sorting/suggested-actions functions, ported from GitLens'
src/plus/launchpad/(origin/main).
It does not include the GitLens provider abstraction (packages/plus/integrations) or @gitkraken/provider-apis clients (provider calls here are hand-written over the injected request); moving those is gkcli#1726 P5b, which is blocked on owner decisions (see root ARCHITECTURE.md).
The package never owns the network: every call takes (or accepts) an injected ApiRequest from @gitkraken/api-tools, and defaults to a fetch requester. Nothing is cached or persisted, and nothing is pushed.
Install
pnpm add @gitkraken/integrations-tools
Open a pull request
import { IntegrationError, openPullRequest, resolvePullRequestTarget } from '@gitkraken/integrations-tools';
const config = { apiBaseUrl: 'https://api.gitkraken.com/', getToken: async () => gitkrakenToken };
const draft = false;
try {
const target = await resolvePullRequestTarget(config, {
remoteUrl: '[email protected]:group/sub/repo.git',
selfHosted, // the servers the user connected to GitKraken: [{ provider, url }]
draft,
});
// target.repository -> { provider: 'gitlab', owner: 'group/sub', name: 'repo', host: 'gitlab.com' }
const pr = await openPullRequest(config, target, {
base: 'main',
head: 'my-branch',
title: 'Add the thing',
body: 'Why the thing is needed.',
draft,
});
console.log(pr.url);
} catch (error) {
if (error instanceof IntegrationError) console.error(error.code, error.message, error.retryable);
}
config is structurally satisfied by account-tools' AccountClientConfig.
resolvePullRequestTarget(config, input) and openPullRequest(config, target, input, options?)
resolvePullRequestTarget returns { repository, token, refreshable }. input takes the remoteUrl, the connected selfHosted servers, and optionally:
reloadSelfHosted(): called once when no provider owns the remote, to re-read servers connected since the host last synced.localTokens:[{ provider, accessToken, isPat, domain?, username? }], used when the cloud has no connection for the provider (for example offline PATs). These are never refreshed.username: the Bitbucket Cloud app-password login, when the token has none.draft: a draft the provider cannot open throwsunsupportedbefore any request. It is only this pre-check; passdrafttoopenPullRequesttoo, or a non-draft pull request is opened.
For a self-hosted provider, the token must be for the remote's server: its domain must be the remote's host and, for Azure DevOps Server, its collection (another server or an unparseable domain is invalid_request), and a local token is chosen by that match, so one connection's token is never sent to another server. An unknown remote is invalid_request, with credentials stripped from the URL in the message. A provider with no token anywhere is not_connected.
openPullRequest calls createPullRequest and adds two things. On provider_auth, a refreshable target (a cloud OAuth token on GitLab, Bitbucket or Azure DevOps) is refreshed once and the create retried once. A refresh GitKraken refuses with 400 or 403 becomes provider_auth. A 5xx, network failure, or abort or timeout of signal while the create request is in flight is not retryable, because the provider may have opened the pull request, and the message says so (cause keeps the original error). An abort before the create request is sent, including one during the token refresh, is rethrown unchanged.
createPullRequest and the token functions below stay available for hosts that need the steps separately.
parseRemoteUrl(remoteUrl, selfHosted?)
Returns { provider, owner, name, azureProject?, host }, or undefined.
- Matching is by exact hostname, never by substring (
notgithub.example.comis not GitHub). Connected self-hosted servers are checked first, in array order (an entry may carry a path such ashttps://host/gitlab, or an Azure DevOps Server collection such ashttps://host/tfs/DefaultCollection, which is required for that provider); then the cloud hostsgithub.com,gitlab.com,bitbucket.org/bitbucket.com, anddev.azure.com/ssh.dev.azure.com/*.visualstudio.com. https,http,sshandgitURLs and the scp form (git@host:path) are supported; userinfo and ports are ignored.- Layouts: GitLab
owneris the full namespace (group/sub); Bitbucket Serverowneris the project key, uppercased unless it is a~userpersonal project, and a leadingscm/is dropped; Azure DevOpsowneris the organization (cloud) or collection name (Server) andazureProjectthe project (a repository named after its project may omit it in the URL).
getProviderToken and refreshProviderToken
getProviderToken(config, provider, signal?) calls GET v1/provider-tokens/{id} and returns a ProviderToken (accessToken, type, isPat, and domain/tokenId/isPrimary/expiresIn when present). For a Bitbucket Cloud app password the host sets username on the token itself; the cloud does not return it. refreshProviderToken(config, provider, accessToken, signal?) rotates an expiring OAuth token and returns the new access token (not for PATs or self-hosted servers). An error thrown after the caller's signal aborted is rethrown unchanged. Callers decide when to refresh: on a provider_auth error from createPullRequest, refresh once and retry.
createPullRequest(input, { token, request?, logger?, signal? })
| Provider | Draft |
|---|---|
github, githubEnterprise | draft field |
gitlab, gitlabSelfHosted | no create-time flag: the title is prefixed with Draft: (unless it already starts with Draft:, [Draft] or (Draft)) |
bitbucket | draft field |
bitbucketServer | unsupported: draft: true throws unsupported and sends nothing (supportsDraft is false) |
azure, azureDevopsServer | isDraft field |
The self-hosted providers take their server URL from token.domain; without one the call throws invalid_request and sends nothing. Azure DevOps Server needs its collection URL there. A Bitbucket Cloud app password needs token.username (the Bitbucket username, not the email). A token for a different provider than input.provider is rejected, so a token is never sent to the wrong host.
Failures are IntegrationErrors with a stable code, status, retryable and provider:
code | When |
|---|---|
not_logged_in | the GitKraken API rejected the caller's own token (token functions) |
not_connected | the provider is not connected to the GitKraken account (token functions) |
unsupported | the provider cannot do what was asked (a draft on Bitbucket Server) |
provider_auth | the provider rejected the connection's token: HTTP 401, 403, or Azure's 203 sign-in page |
rate_limited | HTTP 429, or a GitHub 403 with an exhausted x-ratelimit-remaining or a retry-after header (retryable) |
invalid_request | any other 4xx, with the provider's message (for example "a pull request already exists"), or input refused before any request |
provider_error | 5xx or a network failure (retryable on reads and lookups; not retryable on the create request of openPullRequest, createIssue or addIssueComment, which may have landed), or a 2xx without the created resource or with an invalid body (not retryable: the pull request, issue or comment may have been created) |
Pull-request detail, file content and issue writes
All six take (options, input) with options a ProviderCallOptions (token, request?, logger?, signal?, refresh?).
getPullRequest(options, { id, owner, repo, azureProject?, files? })returns{ pullRequest, warnings }. Withfiles: truethe changed files are listed within gkcli's limits (GitHub and GitLab: 20 pages of 100 files, 512 KB of diffs and a 45 s walk; a file past the budget keeps its name and loses its patch,diffOmitted; GitLab also flags patches omitted by the provider). Bitbucket Cloud lists every file of its diff within the same 512 KB patch budget, Bitbucket Server pageschangesup to 10 pages, both under the same 45 s deadline (a later Bitbucket Server page that fails or times out keeps the earlier files and adds a warning; the Bitbucket Cloud diff is a single request, so a diff that fails or times out fails the whole call with no partial list), Azure DevOps lists none.getPullRequestComments(options, input)returns{ prComments, reviewComments }: conversation and inline comments. GitHub puts both inprCommentsand review summaries inreviewComments; other providers put inline comments inreviewComments. Every page is read; system notes and deleted comments are left out.createPullRequestReview(options, { id, owner, repo, azureProject?, review, approve? })posts thereviewtext as a comment and, withapprove, an approval, in one GitHub review call, or separate calls for other providers. It returns "Your review has been submitted", with a link to the comment or review where the provider gives one. An emptyreviewwithoutapproveis aninvalid_request. When the approval fails after the comment was posted, the error is non-retryable and says the comment was posted. A read before the first write (the Azure DevOps identity lookup for an approval) fails like any read, since nothing was submitted.getFileContent(options, { owner, repo, ref, filePath, azureProject?, maxBytes? })returns the file's text. A file overmaxBytes(default 1 MiB) fails withinvalid_request. The limit caps the returned content, not memory or download: only GitLab (a best-effortHEADforX-Gitlab-Size; a failedHEADfalls through to theGET) and Bitbucket Cloud (the path metadata'ssize) refuse a file before downloading it. GitHub'ssizecomes in the same response as the inlined content, and a raw response'scontent-lengthwith its body, so those are refused after the download but before decoding; otherwise the host'srequestreads the whole body before the check.owneris not required on Azure DevOps Server, where the token's collection URL replaces it.createIssue(options, { title, body?, org?, repo?, labels?, assignees?, issueType?, azureOrg?, azureProject? })returns the createdIssuewith the fields the create response gives.issueTypeis Jira only (defaultTask, project key inrepo). Trello throwsunsupported.addIssueComment(options, { id, comment, org?, repo?, azureOrg?, azureProject? })takes Markdown on Jira (converted) and HTML on Azure DevOps. Jira's Markdown conversion does not support reference-style links ([text][ref]with a[ref]: urldefinition).
getFileContent's ref is a branch, tag or commit SHA on every provider except Azure DevOps, which cannot tell a bare tag from a branch: a full commit SHA reads at that commit, refs/tags/<name> at a tag, and refs/heads/<name> or any other bare name is read as a branch. On Bitbucket Cloud a branch name may contain /. The file lookup first reads path metadata, rejects directories, and fetches the file at the commit returned by that metadata.
For getFileContent the host's request must return the response body as text (or bytes, decoded as UTF-8). A request that pre-parses JSON fails with a non-retryable provider_error. Bitbucket and Azure DevOps return the body verbatim even when the host labels it application/json, so JSONC or other malformed JSON comes back as text.
The three reads refresh the token once on provider_auth (when refresh is set). The three writes (createPullRequestReview, createIssue, addIssueComment) never refresh the token, so a provider_auth error reaches the caller untouched. They retry a throttled request once only where the provider's transport does: GitHub and GitHub Enterprise on a 429 (after its Retry-After, 5 seconds without one) or a 403 with a Retry-After, either only when that wait is at most 30 seconds; Bitbucket Cloud and Server, Jira (Cloud and Server) and Azure DevOps (cloud and server) on a 429. GitLab, Linear and Trello never retry. A 5xx, transport failure, or abort or timeout of signal while a create, comment or review request is in flight is a non-retryable provider_error saying the issue or comment may already exist or the review may have been submitted (cause keeps the original error). An abort or timeout of signal before a write request is sent, including one during a lookup before it, is rethrown unchanged; a 5xx or transport failure of such a lookup (a Linear team, label or user, the Jira Cloud sites, the Azure DevOps identity for an approval) stays retryable. After a posted review comment, a failed approval is non-retryable and says the comment was posted. A Linear GraphQL validation error on the mutation is invalid_request only when the response has no result for the mutation (data or its issueCreate/commentCreate is null), so Linear refused it; with a result present it is a possibly-written provider_error. Errors use the codes of the table above: unsupported for a provider without the capability, invalid_request for missing input or a 4xx, provider_auth, rate_limited and provider_error; a 2xx a write cannot read is a non-retryable provider_error (the review, issue or comment may exist). Jira Cloud never repeats a write on another site after such a response, and never repeats a create or comment after a 5xx, timeout or transport failure (it may exist on the first site). A missing file or ref is invalid_request with status: 404. GitHub and GitLab also fail with invalid_request and no status when a 2xx body has no usable file content (for example a directory on GitHub).
File content limits:
maxBytescaps the returned content, not memory: only GitLab (best-effortHEAD) and Bitbucket Cloud (metadata) check the size before downloading. GitHub'ssizeand a raw response'scontent-lengthare checked after the download but before decoding; otherwise the host'srequestreads the whole body before the check.- Binary files decode lossily: invalid UTF-8 bytes become U+FFFD. A leading UTF-8 BOM is dropped.
- GitHub's contents API does not inline files over 1 MB; those fail with
invalid_request.
Launchpad
What's here
models/launchpad.ts: the priority tables —launchpadActionCategories,launchpadGroups,launchpadCategoryToGroupMap,sharedCategoryToLaunchpadActionCategoryMap,prActionsMap,launchpadPriorityGroups(display priority order:mergeable,blocked,follow-up,needs-review), andlaunchpadGroupLabelMap/actionGroupMap(plain English strings; GitLens' VS Code icon map and@vscode/l10ncalls are dropped, not ported).launchpad.ts:getLaunchpadItemGroups,groupAndSortLaunchpadItems,countLaunchpadItemGroups,sortLaunchpadItems,getSuggestedActions— ported fromlaunchpadProvider.ts, operating on the minimalLaunchpadItemInputinput type instead of GitLens' fullLaunchpadItem(novscode, noopenRepository/local-branch lookups).groupAndSortLaunchpadItems/countLaunchpadItemGroupsnever contain acurrent-branchkey;sortLaunchpadItemskeeps input order for ties.providers.ts:GitHostingProviderId(the eight GitKraken cloud ids, e.g.github,gitlabSelfHosted,azureDevopsServer),normalizeProviderId(storage keys, CLI names and cloud ids to an id, orundefined),providerDisplayName,isSelfHosted.remotes.ts:parseRemoteUrlresolves a git remote to aRemoteRepository({provider, owner, name, azureProject?, host});SelfHostedProviderdescribes a connected self-hosted server ({provider, url}).
Usage
import {
getLaunchpadItemGroups,
getSuggestedActions,
type LaunchpadItemInput,
sortLaunchpadItems,
} from '@gitkraken/integrations-tools';
const items: LaunchpadItemInput[] = [...];
const aiReviewAllowed = hostAiEnabled; // org + user AI setting; required so a missing flag cannot fail open
sortLaunchpadItems(items);
for (const item of items) {
const groups = getLaunchpadItemGroups(item);
const actions = getSuggestedActions(item.actionableCategory, false, aiReviewAllowed);
}
sortLaunchpadItems reorders and returns the same array; groupAndSortLaunchpadItems
also sorts its input array in place. An unsnoozed draft item in the needs-my-review
category appears in both the draft and needs-review groups, but
countLaunchpadItemGroups counts it under draft and excludes it from needs-review.