---
title: "Provider kit"
description: "The building blocks of a provider, from `forges/kit`."
canonical_url: "https://forges.link/contributing/provider-kit"
---
# Provider kit

> The building blocks of a provider, from `forges/kit`.

Import from `forges/kit`. Code that only uses providers imports from `forges` instead. See [Write a provider](https://forges.link/contributing/write-a-provider) for how they fit together.

## Define a provider

### `CapabilityEnv`

What support can depend on once the provider exists.

| Member | Type | Description |
| --- | --- | --- |
| `version?` | `string` | Instance version from `instanceVersion` or `refreshCapabilities()`, when known. |

### `DeclaredSupport`

The support level a provider declares for a verb: a [`Support`](https://forges.link/reference/provider#support-2), or one
of two levels that the capability matrix and `pnpm test:capabilities` read,
and that `capabilities` reports as `true`:

- `'experimental'`: verified, but built on an API the forge marks unstable.
- `'unverified'`: implemented, but no test verifies it against the forge yet.

**one of:**

- [`Support`](https://forges.link/reference/provider#support-2)
- `'experimental'`
- `'unverified'`

### `SupportInput`

A fixed support level, or one computed from the instance version.

**one of:**

- [`DeclaredSupport`](https://forges.link/contributing/provider-kit#declaredsupport)
- `((env: CapabilityEnv) => DeclaredSupport)`

### `ThreadFilter`

The `ThreadQuery` filters that a provider declares in `threads.listFilters` when its listing applies them.

**one of:**

- `'involves'`
- `'mentions'`
- `'milestone'`

### `AlertKind`

The security alert kinds that support can differ by.

**type:** [`Exclude<SecurityAlertKind, 'other'>`](https://forges.link/reference/data-model#securityalertkind)

### `Verb`

A verb whose support does not depend on the thread kind.

**type parameters:** `F`

| Member | Type | Description |
| --- | --- | --- |
| `support` | [`SupportInput`](https://forges.link/contributing/provider-kit#supportinput) | How well the verb is supported. |
| `run` | `F` |  |

### `KindVerb`

A verb whose support depends on the thread kind it is called with. Kinds not listed are unsupported.

**type parameters:** `F`

| Member | Type | Description |
| --- | --- | --- |
| `kinds` | `Partial<Record<ThreadKind, SupportInput>>` | How well each thread kind is supported. |
| `run` | `F` |  |

### `verb()`

Declares a verb whose support does not depend on the thread kind.

```ts
function verb<F>(support: SupportInput, run: F): Verb<F>
```

| Parameter | Type | Description |
| --- | --- | --- |
| `support` | [`SupportInput`](https://forges.link/contributing/provider-kit#supportinput) | How well the verb is supported. |
| `run` | `F` | The function that implements the verb. |

**Returns:** [`Verb<F>`](https://forges.link/contributing/provider-kit#verb)

### `perKind()`

Declares a verb whose support depends on the thread kind.

**Example**

```ts
const threads = {
  get: perKind({ issue: true, pull_request: true }, getThread),
}
```

```ts
function perKind<F>(kinds: Partial<Record<ThreadKind, SupportInput>>, run: F): KindVerb<F>
```

| Parameter | Type | Description |
| --- | --- | --- |
| `kinds` | `Partial<Record<ThreadKind, SupportInput>>` | How well each thread kind is supported. Kinds that are left out are unsupported. |
| `run` | `F` | The function that implements the verb. |

**Returns:** [`KindVerb<F>`](https://forges.link/contributing/provider-kit#kindverb)

### `ProviderSpec`

Everything a provider declares. Methods and capabilities are both derived from it.

**type parameters:** `TExtensions extends object = Record<never, never>`

| Member | Type | Description |
| --- | --- | --- |
| `extensions?` | `TExtensions` | Members that only this forge's providers have, such as `graphql()` on GitHub. They are added to the provider unchanged. |
| `notApplicable?` | `readonly CapabilityPath[]` | Capabilities the forge has no such operation for, reported as `'not_applicable'` rather than `false`. |
| `traits` |  | Capabilities that no single verb carries. |
| `traits.eventKinds` | [`ForgeCapabilities['eventKinds']`](https://forges.link/reference/provider#forgecapabilities) | Whether event kinds come from the forge or are inferred from text. See `ForgeCapabilities.eventKinds`. |
| `traits.authKinds` | [`readonly AuthKind[]`](https://forges.link/reference/providers#authkind) | The auth types the provider accepts. |
| `traits.limits?` | [`TextLimits`](https://forges.link/reference/data-model#textlimits) | Limits on the text the forge accepts. |
| `repos` |  | Listings are declared as pages; core derives the iterables. |
| `repos.get` | `Verb<ReposApi['get']>` |  |
| `repos.listPage` | `Verb<PageOf<ReposApi['list']>>` |  |
| `repos.byOwnerPage?` | `Verb<PageOf<ReposApi['byOwner']>>` |  |
| `repos.labelsPage?` | `Verb<PageOf<ReposApi['labels']>>` |  |
| `repos.createLabel?` | `Verb<ReposApi['createLabel']>` |  |
| `repos.milestonesPage?` | `Verb<PageOf<ReposApi['milestones']>>` |  |
| `repos.issueTypes?` | `Verb<ReposApi['issueTypes']>` |  |
| `repos.collaboratorsPage?` | `Verb<PageOf<ReposApi['collaborators']>>` |  |
| `repos.contributorsPage?` | `Verb<PageOf<ReposApi['contributors']>>` |  |
| `repos.contributorStats?` | `Verb<ReposApi['contributorStats']>` |  |
| `repos.templates?` | `Verb<ReposApi['templates']>` |  |
| `repos.permissionFor?` | `Verb<ReposApi['permissionFor']>` |  |
| `repos.branchRules?` | `Verb<ReposApi['branchRules']>` |  |
| `repos.addCollaborator?` | `Verb<ReposApi['addCollaborator']>` |  |
| `repos.assignableUsersPage?` | `Verb<PageOf<ReposApi['assignableUsers']>>` |  |
| `repos.reviewerCandidatesPage?` | `Verb<PageOf<ReposApi['reviewerCandidates']>>` |  |
| `repos.eventsPage?` | `Verb<(repo: RepoRef, options?: EventFeedOptions) => Promise<Page<ForgeEventInput>>>` | The implementation of `provider.repos.events()`, one page at a time. |
| `users?` |  | `get` is omitted when the forge cannot read an account by login. |
| `orgs?` |  | An organisation's teams and their members. Listings are declared as pages; core derives the iterables. |
| `threads.get` | `ThreadVerb<'get'>` |  |
| `threads.listPage` | `KindVerb<PageOf<ThreadsApi['list']>>` |  |
| `threads.listFilters?` | [`readonly ThreadFilter[]`](https://forges.link/contributing/provider-kit#threadfilter) | The [`ThreadFilter`](https://forges.link/contributing/provider-kit#threadfilter)s that `listPage` applies, or reports with its own warning. Core leaves the others out of the query and adds a `filter_unsupported` warning to the first page. |
| `threads.getMany` | `Verb<ThreadsApi['getMany']>` |  |
| `threads.closingIssuesPage?` | `Verb<PageOf<ThreadsApi['closingIssues']>>` |  |
| `threads.closingPullRequestsPage?` | `Verb<PageOf<ThreadsApi['closingPullRequests']>>` |  |
| `threads.eventsPage` | `Verb<(ref: ThreadRef, options?: ListOptions) => Promise<Page<ForgeEventInput>>>` |  |
| `threads.commentsPage` | `KindVerb<PageOf<ThreadsApi['comments']>>` |  |
| `threads.getComment?` | `ThreadVerb<'getComment'>` |  |
| `threads.createComment?` | `ThreadVerb<'createComment'>` |  |
| `threads.updateComment?` | `ThreadVerb<'updateComment'>` |  |
| `threads.deleteComment?` | `ThreadVerb<'deleteComment'>` |  |
| `threads.hiding?` | `KindVerb<Pick<ThreadsApi, 'hideComment' \| 'unhideComment'>>` | One capability covers hiding and unhiding a comment. |
| `threads.close?` | `ThreadVerb<'close'>` |  |
| `threads.reopen?` | `ThreadVerb<'reopen'>` |  |
| `threads.locking?` | `KindVerb<Pick<ThreadsApi, 'lock' \| 'unlock'>>` | One capability covers locking and unlocking. |
| `threads.create?` | `ThreadVerb<'create'>` |  |
| `threads.update?` | `ThreadVerb<'update'>` |  |
| `threads.setLabels?` | `ThreadVerb<'setLabels'>` |  |
| `threads.addLabels?` | `ThreadVerb<'addLabels'>` |  |
| `threads.removeLabels?` | `ThreadVerb<'removeLabels'>` |  |
| `threads.setMilestone?` | `ThreadVerb<'setMilestone'>` |  |
| `threads.setIssueType?` | `ThreadVerb<'setIssueType'>` |  |
| `threads.reactions?` | `KindVerb<{ [K in 'react' \| 'unreact']: NonNullable<ThreadsApi[K]> }>` | One capability covers reacting and removing a reaction. |
| `threads.reactionsPage?` | `KindVerb<PageOf<ThreadsApi['reactions']>>` | Listing the reactions on a thread or one of its comments. |
| `threads.transfer?` | `Verb<ThreadsApi['transfer']>` |  |
| `threads.markDuplicate?` | `Verb<ThreadsApi['markDuplicate']>` |  |
| `threads.setAssignees?` | `ThreadVerb<'setAssignees'>` |  |
| `threads.requestReview?` | `ThreadVerb<'requestReview'>` |  |
| `threads.merge?` | `Verb<ThreadsApi['merge']>` |  |
| `threads.updateBranch?` | `Verb<ThreadsApi['updateBranch']>` |  |
| `threads.subscriptions?` | `KindVerb<{ [K in 'subscription' \| 'subscribe' \| 'unsubscribe']: NonNullable<ThreadsApi[K]> }>` | One capability covers reading and changing the subscription. |
| `threads.checks?` | `KindVerb<(ref: ThreadRef, options?: BaseOptions) => Promise<Page<Check>>>` |  |
| `threads.reviewsPage?` | `Verb<PageOf<ThreadsApi['reviews']>>` |  |
| `threads.getReview?` | `Verb<ThreadsApi['getReview']>` |  |
| `threads.createReview?` | `Verb<ThreadsApi['createReview']>` |  |
| `threads.submitReview?` | `Verb<ThreadsApi['submitReview']>` |  |
| `threads.replyToReviewComment?` | `Verb<ThreadsApi['replyToReviewComment']>` |  |
| `threads.approve?` | `Verb<ThreadsApi['approve']>` | Omit to derive approval from `createReview`. |
| `threads.filesPage?` | `Verb<PageOf<ThreadsApi['files']>>` |  |
| `threads.commitsPage?` | `Verb<PageOf<ThreadsApi['commits']>>` |  |
| `threads.reviewThreads?` | `Verb<Pick<ThreadsApi, 'resolveReviewThread' \| 'unresolveReviewThread'>>` | One capability covers resolving and unresolving. |
| `threads.reviewThreadsPage?` | `Verb<PageOf<ThreadsApi['reviewThreads']>>` | Every conversation; core applies the `state` filter. |
| `emulated?` |  | Support for the single-item reads core emulates from their listings where the spec declares no endpoint. Each defaults to `'emulated'`, capped by the listing's own support. |
| `checks?` |  | Commit-level checks, beside the pull-level `threads.checks`. |
| `ci?` |  | CI runs and jobs. Listings are declared as pages; core derives the iterables. |
| `contents?` |  | Repository contents. Listings are declared as pages; core derives the iterables. |
| `search?` |  | Cross-repository search. Listings are declared as pages; core derives the iterables. |
| `securityAlerts?` |  | Support per alert kind; `listPage` is called with `kind` unset to list every supported kind. |
| `notifications?` | `{ listPage: Verb<(options?: NotificationListOptions) => Promise<Page<Notification>>> } & { [K in Exclude<keyof NotificationsApi, 'list'>]?: Verb<NonNullable<NotificationsApi[K]>> }` | Omit when the forge has no notifications. `list` is derived from `page`. |
| `installations?` | [`Verb<InstallationsSpec>`](https://forges.link/contributing/provider-kit#verb) | The implementation of `provider.installations`, except for `list()` and `repos()`, which core derives. |
| `webhooks` |  | Managing registered hooks. Listings are declared as pages; core derives the iterables. |
| `webhooks.listPage?` | `Verb<PageOf<WebhooksApi['list']>>` |  |
| `webhooks.create?` | `Verb<WebhooksApi['create']>` |  |
| `webhooks.update?` | `Verb<WebhooksApi['update']>` |  |
| `webhooks.delete?` | `Verb<WebhooksApi['delete']>` |  |
| `webhooks.rotateSecret?` | `Verb<WebhooksApi['rotateSecret']>` |  |
| `webhooks.deliveriesPage?` | `Verb<PageOf<WebhooksApi['deliveries']>>` |  |
| `webhooks.redeliver?` | `Verb<WebhooksApi['redeliver']>` |  |
| `scopes()?` | `(verb: ForgeVerb) => VerbScopes` | Token scopes or app permissions per verb, for `provider.scopesFor()`. |
| `normaliseMarkdown()?` | `(body: string) => string` | The implementation of `provider.normaliseMarkdown()`. Without it, Markdown is returned unchanged. |
| `web?` | [`WebLinks`](https://forges.link/contributing/provider-kit#weblinks) | How the forge's web pages are laid out; omit when they have no stable pattern. |
| `request?` | [`Fetcher`](https://forges.link/contributing/provider-kit#fetcher) | Fetcher behind `request()`, when it differs from the context fetcher. |
| `probeVersion()?` | `() => Promise<string \| undefined>` | Reads the instance version for `refreshCapabilities()`. Omit when capabilities never depend on it. |
| `rateLimits()?` | [`() => RateLimit[]`](https://forges.link/reference/requests#ratelimit) | The implementation of `provider.rateLimits()`, for a provider whose requests bypass its fetchers. |

### `ProviderBase`

The options, the identity and the resolved URLs that provider hooks receive.

**type parameters:** `TOptions, TState`

| Member | Type | Description |
| --- | --- | --- |
| `options` | `TOptions` |  |
| `forge` | [`ForgeKind`](https://forges.link/reference/data-model#forgekind) |  |
| `instance` | [`ForgeInstance`](https://forges.link/reference/data-model#forgeinstance) |  |
| `baseUrl` | `string` | API base after defaults and the API path are applied. |
| `headers` | `Record<string, string>` | Default headers: the definition's, plus `user-agent` outside browsers or when the caller sets one. |
| `origin` |  | Error context for this provider. |
| `origin.forge` | [`ForgeKind`](https://forges.link/reference/data-model#forgekind) |  |
| `origin.instance` | [`ForgeInstance`](https://forges.link/reference/data-model#forgeinstance) |  |
| `state` | `TState` | State passed to `derive()`, or created by `prepare()`. |

### `ProviderContext`

The argument of `setup()`: the base, the fetchers and `derive()`.

**type parameters:** `TOptions, TState`

**extends:** [`ProviderBase<TOptions, TState>`](https://forges.link/contributing/provider-kit#providerbase)

| Member | Type | Description |
| --- | --- | --- |
| `fetcher` | [`Fetcher`](https://forges.link/contributing/provider-kit#fetcher) | Authenticated with the definition's `authHeaders`. |
| `createFetcher()` | `(overrides: Partial<FetcherOptions> & { baseUrl: string }) => Fetcher` | Another fetcher with the same timeout, `fetch` and error context. It sends no credentials unless it sets its own `authHeaders`. Its budgets count towards `provider.rateLimits()` only when neither it nor `fetcher` sends credentials. |
| `derive()` | [`(options: TOptions, state?: TState) => ForgeProvider`](https://forges.link/reference/provider) | Another provider from the same definition, for example one per app installation. |
| `options` | `TOptions` | Inherited from [`ProviderBase`](https://forges.link/contributing/provider-kit#providerbase). |
| `forge` | [`ForgeKind`](https://forges.link/reference/data-model#forgekind) | Inherited from [`ProviderBase`](https://forges.link/contributing/provider-kit#providerbase). |
| `instance` | [`ForgeInstance`](https://forges.link/reference/data-model#forgeinstance) | Inherited from [`ProviderBase`](https://forges.link/contributing/provider-kit#providerbase). |
| `baseUrl` | `string` | API base after defaults and the API path are applied. Inherited from [`ProviderBase`](https://forges.link/contributing/provider-kit#providerbase). |
| `headers` | `Record<string, string>` | Default headers: the definition's, plus `user-agent` outside browsers or when the caller sets one. Inherited from [`ProviderBase`](https://forges.link/contributing/provider-kit#providerbase). |
| `origin` |  | Error context for this provider. Inherited from [`ProviderBase`](https://forges.link/contributing/provider-kit#providerbase). |
| `origin.forge` | [`ForgeKind`](https://forges.link/reference/data-model#forgekind) | Inherited from [`ProviderBase`](https://forges.link/contributing/provider-kit#providerbase). |
| `origin.instance` | [`ForgeInstance`](https://forges.link/reference/data-model#forgeinstance) | Inherited from [`ProviderBase`](https://forges.link/contributing/provider-kit#providerbase). |
| `state` | `TState` | State passed to `derive()`, or created by `prepare()`. Inherited from [`ProviderBase`](https://forges.link/contributing/provider-kit#providerbase). |

### `ProviderDefinition`

The defaults, the authentication and the `setup()` of a forge.

**type parameters:** `TOptions extends ForgeOptionsBase, TState = undefined, HasWeb extends boolean = boolean, TExtensions extends object = Record<never, never>`

| Member | Type | Description |
| --- | --- | --- |
| `forge` | [`ForgeKind`](https://forges.link/reference/data-model#forgekind) |  |
| `experimental?` | `true` | The forge's API as a whole is unstable, so the provider can change with it. |
| `anonymous?` | `true \| 'webhooks'` | Accepts a missing `auth` as `{ type: 'anonymous' }`: core then sends no credentials and marks writes, notifications, subscriptions, installations and the account's repository list unsupported. `'webhooks'` marks every verb unsupported, for a forge whose API needs credentials but whose webhook deliveries can be verified without them. |
| `baseUrl` | `string` | Default `baseUrl` when the caller passes none. |
| `apiPath?` | `string` | Appended to `baseUrl` unless already present, for example `/api/v4`. |
| `instance()?` | `(host: string) => string` | Maps the API host to the instance host, for example `api.github.com` to `github.com`. |
| `headers?` | `Record<string, string>` |  |
| `prepare()?` | [`(base: ProviderBase<TOptions, TState \| undefined>) => TState`](https://forges.link/contributing/provider-kit#providerbase) | Builds per-provider state once; receives the state given to `derive()`, if any. |
| `authHeaders()?` | `(base: ProviderBase<TOptions, TState>) => FetcherOptions['authHeaders']` | Resolves the credential headers of each request. |
| `query?` | `Record<string, string>` | Query parameters for every request, such as an API version; see `FetcherOptions.query`. |
| `hasWeb?` | `HasWeb` | Whether the forge has a website: `setup()` must then return `web`, and the provider's `webOrigin` is typed `string`. |
| `setup()` | `(ctx: ProviderContext<TOptions, TState>) => HasWeb extends true ? ProviderSpec<TExtensions> & { web: WebLinks } : ProviderSpec<TExtensions>` | Declares the verbs and the web links of one provider. |
| `webhooks?` | [`WebhookHandlers<TOptions>`](https://forges.link/contributing/provider-kit#webhookhandlers) | Delivery verification and translation. Omit it and `webhooks.ingest()` is unsupported. |

### `WebhookHandlers`

Verifies and translates deliveries for one provider; built once per instance from its context.

**type parameters:** `TOptions`

**type:** `(ctx: Omit<ProviderContext<TOptions, unknown>, 'state' | 'derive'>) => { events: WebhookEventType[] verify: (delivery: WebhookDelivery) => Promise<boolean> translate: (delivery: WebhookDelivery) => ForgeEventInput[] | Promise<ForgeEventInput[]> }`

### `defineForgeProvider()`

Defines a forge provider. Returns the function end users call to create
one, for example `github({ auth })`. Nothing touches the network until a
method of the provider is called.

```ts
function defineForgeProvider<TOptions extends ForgeOptionsBase, TState = undefined, HasWeb extends boolean = boolean, Forge extends ForgeKind = ForgeKind, TExtensions extends object = Record<never, never>>(definition: ProviderDefinition<TOptions, TState, HasWeb, TExtensions>): ProviderFactoryFunction<TOptions, HasWeb, Forge, ForgeProvider<HasWeb> & TExtensions>
```

| Parameter | Type | Description |
| --- | --- | --- |
| `definition` | [`ProviderDefinition<TOptions, TState, HasWeb, TExtensions>`](https://forges.link/contributing/provider-kit#providerdefinition) | The defaults, authentication and setup of the forge. |

**Returns:** `ProviderFactoryFunction<TOptions, HasWeb, Forge, ForgeProvider<HasWeb> & TExtensions>`

## Capability table

### `CapabilityEntry`

One row of the capability table: the `ForgeProvider` verbs it covers, where
they are declared on `ProviderSpec`, and the key their support lands on in
`ForgeCapabilities`. `capabilitiesOf()`, `can()` and the capability matrix
derive from the table.

| Member | Type | Description |
| --- | --- | --- |
| `capability` | `string` | The first verb the row covers, or the name of a trait such as `limits`, dot-separated. |
| `spec?` | `string` | Where the verb is declared on `ProviderSpec`, dot-separated. |
| `verbs?` | `readonly string[]` | Verbs on `ForgeProvider` this capability covers, each with its own key on `ForgeCapabilities`. |
| `listings?` | `readonly string[]` | Verbs that return a `ForgeListing`, declared on `ProviderSpec` as their page, such as `threads.commentsPage`. |
| `perKind?` | `boolean` | Support is declared per thread kind. |
| `derived?` | `'experimental' \| 'webhook' \| 'threadEvents' \| 'getComment' \| 'getReview' \| 'ciJob' \| 'commitComment' \| 'subscriptionSet' \| 'approve' \| 'alertKinds' \| 'eventKinds' \| 'authKinds' \| 'limits'` | The capability is computed by core rather than read from a declared verb. |
| `write?` | `boolean` | The verbs change state, so `readOnly` and anonymous providers reject them. |
| `account?` | `boolean` | The verbs need an account, so anonymous providers reject them. |

### `CAPABILITY_TABLE`

Every capability with the verbs it covers and the flags that gate it, in the order the capability matrix lists them.

**type:** [`readonly CapabilityEntry[]`](https://forges.link/contributing/provider-kit#capabilityentry)

## Requests

### `FetcherOptions`

Options for `createFetcher()`.

| Member | Type | Default | Description |
| --- | --- | --- | --- |
| `baseUrl` | `string` |  |  |
| `fetch?` | [`FetchLike`](https://forges.link/reference/requests#fetchlike) |  | Injected for tests and for runtimes with a non-global fetch. |
| `timeout?` | `number` | `30000` | Timeout in milliseconds (headers only for streams). |
| `headers?` | `Record<string, string>` |  | Default headers, sent only to the API origin. |
| `authHeaders()?` | `() => Promise<Record<string, string>> \| Record<string, string>` |  | Credentials resolved before each API-origin request. |
| `authenticated?` | `boolean` |  | Requests carry credentials that `authHeaders` does not set, for example through a `fetch` that signs them. |
| `query?` | `Record<string, string>` |  | API-origin query defaults; request parameters take precedence. |
| `context?` | [`ForgeErrorContext`](https://forges.link/reference/errors#forgeerrorcontext) |  | Attached to every error the fetcher throws. |
| `onRetry()?` | `(retry: { url: string, method: string, wait: number }) => void` |  | Called before a request is retried. A rate limit with a `retry-after` of at most a minute is retried once, after that wait. |
| `onRateLimit()?` | [`(event: { url: string, method: string, rateLimit: RateLimit }) => void`](https://forges.link/reference/requests#ratelimit) |  | Called with the rate limit that a response from the base URL's origin reports, including a response that fails or is `304 Not Modified`. Responses without rate limit headers don't call it. |

### `RequestOptions`

Options for one request of a fetcher.

**extends:** `Omit<RequestInit, 'signal'>`

| Member | Type | Description |
| --- | --- | --- |
| `query?` | `Record<string, string \| number \| boolean \| undefined>` | Query parameters. Parameters that are `undefined` are left out. |
| `signal?` | `AbortSignal` |  |
| `etag?` | `string` | Send `If-None-Match`, and resolve with `notModified` instead of throwing. |
| `json?` | `unknown` | Serialised as the JSON request body, with a matching `content-type`. |
| `mapError()?` | `(error: unknown) => unknown` | Rewrites a failure from this request, for endpoints whose statuses mean something specific. |

### `PaginateOptions`

Options for reading one page of a paginated endpoint.

**extends:** [`RequestOptions`](https://forges.link/contributing/provider-kit#requestoptions)

| Member | Type | Default | Description |
| --- | --- | --- | --- |
| `select()?` | `(body: unknown, linkNext?: string) => { items: unknown[], next?: string, total?: number }` |  | Reads items and the next page URL from a response body, for APIs that paginate in the body (Bitbucket's `values` / `next`). Without it, the body is the item array and the next page comes from the `Link` header. `linkNext` is the `Link` header's next URL, for APIs that wrap items in the body but still paginate with `Link`. `total` is the item total the body reports, such as a search's `total_count`. |
| `conditional?` | `boolean` | `true` | Whether the first page sends `cursor.etag` as `If-None-Match` and reports its validator in `etag`. Turn it off for a page that is built from more than this one response. |
| `query?` | `Record<string, string \| number \| boolean \| undefined>` |  | Query parameters. Parameters that are `undefined` are left out. Inherited from [`RequestOptions`](https://forges.link/contributing/provider-kit#requestoptions). |
| `signal?` | `AbortSignal` |  | Inherited from [`RequestOptions`](https://forges.link/contributing/provider-kit#requestoptions). |
| `etag?` | `string` |  | Send `If-None-Match`, and resolve with `notModified` instead of throwing. Inherited from [`RequestOptions`](https://forges.link/contributing/provider-kit#requestoptions). |
| `json?` | `unknown` |  | Serialised as the JSON request body, with a matching `content-type`. Inherited from [`RequestOptions`](https://forges.link/contributing/provider-kit#requestoptions). |
| `mapError()?` | `(error: unknown) => unknown` |  | Rewrites a failure from this request, for endpoints whose statuses mean something specific. Inherited from [`RequestOptions`](https://forges.link/contributing/provider-kit#requestoptions). |

### `FetchResult`

A parsed response.

**type parameters:** `T`

| Member | Type | Description |
| --- | --- | --- |
| `data` | `T` |  |
| `response` | `Response` |  |
| `notModified` | `boolean` | The server answered `304 Not Modified` to the `etag` that the request sent. |
| `cursor?` | [`Cursor`](https://forges.link/reference/requests#cursor) | Where the next page starts, when there is one. |
| `total?` | `number` | The total number of items the listing reports, where the response carries one. |
| `etag?` | `string` | The validator of a listing's first page, from `Fetcher.page`. |

### `Fetcher`

A client for one forge API. It adds credentials, applies the timeout and retries, and maps failures to errors.

| Member | Type | Description |
| --- | --- | --- |
| `raw()` | [`(path: string, options?: RequestOptions) => Promise<Response>`](https://forges.link/contributing/provider-kit#requestoptions) | Sends a request and returns the response unparsed. |
| `stream()` | `(path: string, options?: RequestOptions) => Promise<RawResponse>` | Bytes as they arrive, through the same timeout and error mapping as `Fetcher.json`. HTTP(S) download redirects to another origin omit all headers and credentials. HTTPS downloads cannot redirect to HTTP. Where `fetch` hides redirects (browsers), the runtime follows GET and HEAD under its own header rules. |
| `json()` | `(path: string, options?: RequestOptions) => Promise<FetchResult<T>>` | Sends a request and parses the JSON body. |
| `page()` | `(path: string, options?: PaginateOptions & { cursor?: Cursor }) => Promise<FetchResult<T[]>>` | One page: `path` with its query, or `cursor.nextUrl` when given. A first page, whose cursor has neither `nextUrl` nor `token`, sends `cursor.etag` as `If-None-Match` and reports the response's validator in `etag`. |
| `items()` | [`(path: string, options?: PaginateOptions) => AsyncGenerator<T>`](https://forges.link/contributing/provider-kit#paginateoptions) | Every item across every page, in order. |
| `resolve()` | [`(path: string, query?: RequestOptions['query']) => string`](https://forges.link/contributing/provider-kit#requestoptions) | The absolute URL of a path and query, without sending a request. |

### `parseLinkHeader()`

Parses an RFC 5988 `Link` header into a map of rel to URL.

```ts
function parseLinkHeader(header: string | null | undefined): Record<string, string>
```

| Parameter | Type |
| --- | --- |
| `header` | `string \| null \| undefined` |

**Returns:** `Record<string, string>`

### `createFetcher()`

Creates a fetcher for one forge API.

```ts
function createFetcher(options: FetcherOptions): Fetcher
```

| Parameter | Type | Description |
| --- | --- | --- |
| `options` | [`FetcherOptions`](https://forges.link/contributing/provider-kit#fetcheroptions) | The base URL and the credentials, timeout and error context of every request. |

**Returns:** [`Fetcher`](https://forges.link/contributing/provider-kit#fetcher)

### `CreateRequestOptions`

Options for `createRequest()`.

| Member | Type | Description |
| --- | --- | --- |
| `readOnly()?` | `(method: string, path: string) => Error` | Error for mutating requests. |

### `createRequest()`

Builds a provider's `request()` escape hatch on top of its fetcher.

```ts
function createRequest(fetcher: Fetcher, createOptions: CreateRequestOptions = {}): ForgeRequest
```

| Parameter | Type | Description |
| --- | --- | --- |
| `fetcher` | [`Fetcher`](https://forges.link/contributing/provider-kit#fetcher) | The fetcher to send requests with. |
| `createOptions?` | [`CreateRequestOptions`](https://forges.link/contributing/provider-kit#createrequestoptions) | Where to reject writes, for a read-only provider. Defaults to `{}`. |

**Returns:** [`ForgeRequest`](https://forges.link/reference/requests#forgerequest)

## Webhooks and events

### `eventAction()`

Normalises a forge-native verb (`closed`, `close`, `synchronize`, ...) into an [`EventAction`](https://forges.link/reference/data-model#eventaction).

```ts
function eventAction(raw: string | undefined): EventAction | undefined
```

| Parameter | Type |
| --- | --- |
| `raw` | `string \| undefined` |

**Returns:** [`EventAction | undefined`](https://forges.link/reference/data-model#eventaction)

### `completeEvent()`

Fills `action` from `actionRaw`, or from the last `.`/`:` segment of
`kindRaw`, falling back to the kind's default verb, then `other`.

```ts
function completeEvent(event: ForgeEventInput): ForgeEvent
```

| Parameter | Type |
| --- | --- |
| `event` | [`ForgeEventInput`](https://forges.link/contributing/provider-kit#forgeeventinput) |

**Returns:** [`ForgeEvent`](https://forges.link/reference/data-model#forgeevent)

### `reviewState()`

Normalises a forge-native review verdict (`APPROVED`, `changes_requested`, ...) into a [`ReviewState`](https://forges.link/reference/data-model#reviewstate).

```ts
function reviewState(raw: string | undefined): ReviewState
```

| Parameter | Type |
| --- | --- |
| `raw` | `string \| undefined` |

**Returns:** [`ReviewState`](https://forges.link/reference/data-model#reviewstate)

### `verifyHmacSignature()`

Checks a hex HMAC-SHA256 of the raw body, sent in the first of `header`
present, after an optional `prefix` such as `sha256=`. The delivery's own
`secret` takes precedence over the provider's.

```ts
function verifyHmacSignature(delivery: WebhookDelivery, secret: string | undefined, { header, prefix = '' }: { header: string | readonly string[], prefix?: string }): Promise<boolean>
```

| Parameter | Type |
| --- | --- |
| `delivery` | [`WebhookDelivery`](https://forges.link/reference/data-model#webhookdelivery) |
| `secret` | `string \| undefined` |
| `{ header, prefix = '' }` | `{ header: string \| readonly string[], prefix?: string }` |

**Returns:** `Promise<boolean>`

### `verifySharedToken()`

Checks a secret sent verbatim in `header`.

```ts
function verifySharedToken(delivery: WebhookDelivery, secret: string | undefined, header: string): boolean
```

| Parameter | Type |
| --- | --- |
| `delivery` | [`WebhookDelivery`](https://forges.link/reference/data-model#webhookdelivery) |
| `secret` | `string \| undefined` |
| `header` | `string` |

**Returns:** `boolean`

### `RefChange`

One ref update in a push delivery.

| Member | Type | Description |
| --- | --- | --- |
| `ref` | `string` | A full ref such as `refs/heads/main`, or a bare name when `refType` is given. |
| `refType?` | `'branch' \| 'tag'` | Whether the ref is a branch or a tag. |
| `before?` | `string` |  |
| `after?` | `string` |  |
| `created?` | `boolean` |  |
| `deleted?` | `boolean` |  |
| `forced?` | `boolean` |  |
| `commits?` | [`PushCommit[]`](https://forges.link/reference/data-model#pushcommit) |  |
| `commitCount?` | `number` | Commits pushed, when the forge reports more than it sends. |

### `refEvent()`

The kind, detail and summary of one ref update in a push: a deletion, a creation, or new commits. Without
`commits` or `commitCount`, the detail has no `commitCount`.

```ts
function refEvent(who: string, change: RefChange): Pick<ForgeEventInput, 'kind' | 'action' | 'detail' | 'summary'>
```

| Parameter | Type |
| --- | --- |
| `who` | `string` |
| `change` | [`RefChange`](https://forges.link/contributing/provider-kit#refchange) |

**Returns:** [`Pick<ForgeEventInput, 'kind' | 'action' | 'detail' | 'summary'>`](https://forges.link/contributing/provider-kit#forgeeventinput)

### `NativeEventMap`

Native event names per normalised kind, as a forge names them in a hook subscription.

**type:** [`Partial<Record<EventKind, readonly string[]>>`](https://forges.link/reference/data-model#eventkind)

### `nativeEventsFor()`

The forge's own event names for `events`, plus any `nativeEvents` passed through unchanged.

```ts
function nativeEventsFor(map: NativeEventMap, events: EventKind[] | undefined, nativeEvents: string[] | undefined): string[]
```

| Parameter | Type |
| --- | --- |
| `map` | [`NativeEventMap`](https://forges.link/contributing/provider-kit#nativeeventmap) |
| `events` | [`EventKind[] \| undefined`](https://forges.link/reference/data-model#eventkind) |
| `nativeEvents` | `string[] \| undefined` |

**Returns:** `string[]`

## Cryptography

### `toBase64()`

Base64 for arbitrary bytes, a byte at a time so a large buffer cannot overflow the call stack.

```ts
function toBase64(bytes: Uint8Array): string
```

| Parameter | Type |
| --- | --- |
| `bytes` | `Uint8Array` |

**Returns:** `string`

### `hmacSha256Hex()`

Lowercase hex HMAC-SHA256 of `body` under `secret`.

```ts
function hmacSha256Hex(secret: string, body: string | Uint8Array): Promise<string>
```

| Parameter | Type |
| --- | --- |
| `secret` | `string` |
| `body` | `string \| Uint8Array` |

**Returns:** `Promise<string>`

### `timingSafeEqual()`

Constant-time comparison of two strings. The time taken depends only on the
length of `a`, so pass the untrusted value as `a`.

```ts
function timingSafeEqual(a: string, b: string): boolean
```

| Parameter | Type |
| --- | --- |
| `a` | `string` |
| `b` | `string` |

**Returns:** `boolean`

### `JwtClaims`

The claims of a signed JWT. Other claims are passed through.

| Member | Type | Description |
| --- | --- | --- |
| `iss` | `string` | The issuer, such as the app ID. |
| `iat` | `number` | When the token was issued, in seconds since the epoch. |
| `exp` | `number` | When the token expires, in seconds since the epoch. |

### `signRs256Jwt()`

Signs an RS256 JWT with a PEM-encoded RSA private key.

```ts
function signRs256Jwt(privateKeyPem: string, claims: JwtClaims): Promise<string>
```

| Parameter | Type |
| --- | --- |
| `privateKeyPem` | `string` |
| `claims` | [`JwtClaims`](https://forges.link/contributing/provider-kit#jwtclaims) |

**Returns:** `Promise<string>`

### `headerValue()`

The value of a header, whatever the casing of `name`, from a `Headers` object or a plain record.

```ts
function headerValue(headers: Headers | Record<string, string>, name: string): string | undefined
```

| Parameter | Type |
| --- | --- |
| `headers` | `Headers \| Record<string, string>` |
| `name` | `string` |

**Returns:** `string | undefined`

### `bodyText()`

A request body as text.

```ts
function bodyText(body: string | Uint8Array): string
```

| Parameter | Type |
| --- | --- |
| `body` | `string \| Uint8Array` |

**Returns:** `string`

### `sha256Hex()`

Lowercase hex SHA-256 of `body`.

```ts
function sha256Hex(body: string | Uint8Array): Promise<string>
```

| Parameter | Type |
| --- | --- |
| `body` | `string \| Uint8Array` |

**Returns:** `Promise<string>`

### `signEdDsaJwt()`

Signs an EdDSA (Ed25519) JWT with a PKCS#8 PEM private key. `kid` goes in the JOSE header.

```ts
function signEdDsaJwt(privateKeyPem: string, claims: JwtClaims, kid?: string): Promise<string>
```

| Parameter | Type |
| --- | --- |
| `privateKeyPem` | `string` |
| `claims` | [`JwtClaims`](https://forges.link/contributing/provider-kit#jwtclaims) |
| `kid?` | `string` |

**Returns:** `Promise<string>`

### `Ed25519Jwk`

An Ed25519 public key in JWK form, as served from a JWKS endpoint.

| Member | Type | Description |
| --- | --- | --- |
| `kty` | `'OKP'` | The key type, always `OKP`. |
| `crv` | `'Ed25519'` | The curve, always `Ed25519`. |
| `x` | `string` | The public key, base64url encoded. |
| `kid?` | `string` |  |

### `verifyEd25519()`

Verifies an Ed25519 signature (base64) over `data` with a JWK public key.

```ts
function verifyEd25519(jwk: Ed25519Jwk, data: string | Uint8Array, signatureBase64: string): Promise<boolean>
```

| Parameter | Type |
| --- | --- |
| `jwk` | [`Ed25519Jwk`](https://forges.link/contributing/provider-kit#ed25519jwk) |
| `data` | `string \| Uint8Array` |
| `signatureBase64` | `string` |

**Returns:** `Promise<boolean>`

### `hmacSha256Base64()`

Base64 HMAC-SHA256 of `body` under `secret`.

```ts
function hmacSha256Base64(secret: string, body: string | Uint8Array): Promise<string>
```

| Parameter | Type |
| --- | --- |
| `secret` | `string` |
| `body` | `string \| Uint8Array` |

**Returns:** `Promise<string>`

## Helpers

### `supportOnly()`

Marks every declared verb unsupported except the capabilities in `keep` and
anything under them, for a credential that reaches only part of the API.

**Example**

```ts
return appItself ? supportOnly(spec, ['installations']) : spec
```

```ts
function supportOnly<T extends ProviderSpec>(spec: T, keep: readonly string[]): T
```

| Parameter | Type | Description |
| --- | --- | --- |
| `spec` | `T` | The spec that `setup()` declares. |
| `keep` | `readonly string[]` | Capability paths, such as `installations`, that stay as declared. |

**Returns:** `T`

### `fromBase64()`

Decodes base64, tolerating the newlines GitHub and Gitea wrap it in.

```ts
function fromBase64(value: string): Uint8Array<ArrayBuffer>
```

| Parameter | Type |
| --- | --- |
| `value` | `string` |

**Returns:** `Uint8Array<ArrayBuffer>`

### `toFileContent()`

Shapes bytes as the caller asked: UTF-8 text for `as: 'text'`, bytes
otherwise. Rejects with [`ContentNotTextError`](https://forges.link/reference/errors#contentnottexterror) when text was asked for
and the bytes are not valid UTF-8.

```ts
function toFileContent(bytes: Uint8Array, file: FileMetadata, options: FileOptions | undefined, context?: { forge?: string, instance?: string }): FileContent
```

| Parameter | Type |
| --- | --- |
| `bytes` | `Uint8Array` |
| `file` | [`FileMetadata`](https://forges.link/reference/data-model#filemetadata) |
| `options` | [`FileOptions \| undefined`](https://forges.link/reference/data-model#fileoptions) |
| `context?` | `{ forge?: string, instance?: string }` |

**Returns:** [`FileContent`](https://forges.link/reference/data-model#filecontent)

### `toMergeError()`

Maps a generic merge-endpoint failure onto [`MergeBlockedError`](https://forges.link/reference/data-model#mergeblockederror) or [`MergeConflictError`](https://forges.link/reference/data-model#mergeconflicterror).

```ts
function toMergeError(error: unknown): unknown
```

| Parameter | Type |
| --- | --- |
| `error` | `unknown` |

**Returns:** `unknown`

### `soleMergeMethod()`

Picks the only allowed merge method, or throws [`MergeMethodRequiredError`](https://forges.link/reference/data-model#mergemethodrequirederror).

```ts
function soleMergeMethod(allowed: Partial<Record<MergeMethod, boolean | undefined>>, context?: ForgeErrorContext): MergeMethod
```

| Parameter | Type |
| --- | --- |
| `allowed` | [`Partial<Record<MergeMethod, boolean \| undefined>>`](https://forges.link/reference/data-model#mergemethod) |
| `context?` | [`ForgeErrorContext`](https://forges.link/reference/errors#forgeerrorcontext) |

**Returns:** [`MergeMethod`](https://forges.link/reference/data-model#mergemethod)

### `reactionContent()`

The normalised name for a forge-native reaction name, or `'other'` where there is none.

```ts
function reactionContent(raw: string): ReactionContent | 'other'
```

| Parameter | Type |
| --- | --- |
| `raw` | `string` |

**Returns:** [`ReactionContent | 'other'`](https://forges.link/reference/data-model#reactioncontent)

### `ForgeEventInput`

A [`ForgeEvent`](https://forges.link/reference/data-model#forgeevent) as a provider builds it; core derives `action` when it is absent.

**type:** `Omit<ForgeEvent, 'action'> & { action?: EventAction }`

### `forgeIterable()`

Wraps a generator so warnings it reports are collected on the returned
iterable rather than interrupting iteration.

```ts
function forgeIterable<T>(run: (warn: (warning: ForgeWarning) => void) => AsyncIterable<T>): ForgeIterable<T>
```

| Parameter | Type |
| --- | --- |
| `run` | [`(warn: (warning: ForgeWarning) => void) => AsyncIterable<T>`](https://forges.link/reference/requests#forgewarning) |

**Returns:** `ForgeIterable<T>`

### `iteratePages()`

Drives a `page()` function until it reports no further cursor, collecting page warnings.

```ts
function iteratePages<T, O extends { cursor?: Cursor } = ListOptions>(page: (options: O) => Promise<Page<T>>, options: O = {} as O): ForgeIterable<T>
```

| Parameter | Type | Description |
| --- | --- | --- |
| `page` | `(options: O) => Promise<Page<T>>` |  |
| `options?` | `O` | Defaults to `{} as O`. |

**Returns:** `ForgeIterable<T>`

### `toWarning()`

Turns a caught error into a serialisable warning.

```ts
function toWarning(code: string, error: unknown, subject?: string): ForgeWarning
```

| Parameter | Type |
| --- | --- |
| `code` | `string` |
| `error` | `unknown` |
| `subject?` | `string` |

**Returns:** [`ForgeWarning`](https://forges.link/reference/requests#forgewarning)

### `mapConcurrent()`

Maps with at most `limit` calls in flight, preserving order. Once a call rejects, no further calls start.

```ts
function mapConcurrent<T, R>(items: readonly T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]>
```

| Parameter | Type |
| --- | --- |
| `items` | `readonly T[]` |
| `limit` | `number` |
| `fn` | `(item: T) => Promise<R>` |

**Returns:** `Promise<R[]>`

### `getManyConcurrently()`

`threads.getMany` for forges without a batch endpoint. A rate limit or a rejected credential rejects the call; other failures become per-item warnings.

```ts
function getManyConcurrently(refs: ThreadRef[], get: (ref: ThreadRef, options?: BaseOptions) => Promise<Thread>, options: BaseOptions = {}): Promise<GetManyResult[]>
```

| Parameter | Type | Description |
| --- | --- | --- |
| `refs` | [`ThreadRef[]`](https://forges.link/reference/data-model#threadref) |  |
| `get` | `(ref: ThreadRef, options?: BaseOptions) => Promise<Thread>` |  |
| `options?` | [`BaseOptions`](https://forges.link/reference/requests#baseoptions) | Defaults to `{}`. |

**Returns:** [`Promise<GetManyResult[]>`](https://forges.link/reference/data-model#getmanyresult)

### `versionAtLeast()`

Compares dotted numeric versions, ignoring any suffix after the numbers.

```ts
function versionAtLeast(version: string | undefined, minimum: string): boolean
```

| Parameter | Type |
| --- | --- |
| `version` | `string \| undefined` |
| `minimum` | `string` |

**Returns:** `boolean`

### `toDate()`

Reads a timestamp from a forge response, or `undefined` when it is empty or not a date.

```ts
function toDate(value: string | number | null | undefined): Date | undefined
```

| Parameter | Type |
| --- | --- |
| `value` | `string \| number \| null \| undefined` |

**Returns:** `Date | undefined`

### `hostOf()`

The host of `baseUrl`, including the port when there is one.

```ts
function hostOf(baseUrl: string): string
```

| Parameter | Type |
| --- | --- |
| `baseUrl` | `string` |

**Returns:** `string`

### `requireThread()`

Narrows a ref to one a provider can address, or throws [`UnresolvedThreadError`](https://forges.link/reference/errors#unresolvedthreaderror).

```ts
function requireThread(ref: ThreadRef, context?: ForgeErrorContext): ResolvedThreadRef
```

| Parameter | Type |
| --- | --- |
| `ref` | [`ThreadRef`](https://forges.link/reference/data-model#threadref) |
| `context?` | [`ForgeErrorContext`](https://forges.link/reference/errors#forgeerrorcontext) |

**Returns:** [`ResolvedThreadRef`](https://forges.link/reference/data-model#resolvedthreadref)

### `requireIssueOrPull()`

Narrows a ref to an issue or pull request, or throws
[`UnsupportedOperationError`](https://forges.link/reference/errors#unsupportedoperationerror) naming the verb that needs one.

```ts
function requireIssueOrPull(ref: ThreadRef, context: ForgeErrorContext, verb: string): ResolvedThreadRef & { kind: 'issue' | 'pull_request' }
```

| Parameter | Type |
| --- | --- |
| `ref` | [`ThreadRef`](https://forges.link/reference/data-model#threadref) |
| `context` | [`ForgeErrorContext`](https://forges.link/reference/errors#forgeerrorcontext) |
| `verb` | `string` |

**Returns:** [`ResolvedThreadRef & { kind: 'issue' | 'pull_request' }`](https://forges.link/reference/data-model#resolvedthreadref)

### `resolveToken()`

The token in `auth`, read again on every call when it is a function.

```ts
function resolveToken(auth: TokenAuth): Promise<string>
```

| Parameter | Type |
| --- | --- |
| `auth` | [`TokenAuth`](https://forges.link/reference/providers#tokenauth) |

**Returns:** `Promise<string>`

### `actorLogin()`

A login from either a login string or an actor.

```ts
function actorLogin(actor: string | Actor): string
```

| Parameter | Type |
| --- | --- |
| `actor` | [`string \| Actor`](https://forges.link/reference/data-model#actor) |

**Returns:** `string`

### `toPage()`

Maps one fetched page into a [`Page`](https://forges.link/reference/requests#page). The cursor is kept only when there is a next page.

```ts
function toPage<R, T>(result: FetchResult<R[]>, map: (raw: R) => T | undefined, warnings?: ForgeWarning[]): Page<T>
```

| Parameter | Type |
| --- | --- |
| `result` | [`FetchResult<R[]>`](https://forges.link/contributing/provider-kit#fetchresult) |
| `map` | `(raw: R) => T \| undefined` |
| `warnings?` | [`ForgeWarning[]`](https://forges.link/reference/requests#forgewarning) |

**Returns:** `Page<T>`

### `ListingExtras`

Extra options for a listing: the query, how to select the items and map errors, and where to collect warnings.

**extends:** [`Pick<PaginateOptions, 'query' | 'select' | 'mapError'>`](https://forges.link/contributing/provider-kit#paginateoptions)

| Member | Type | Description |
| --- | --- | --- |
| `warnings?` | [`ForgeWarning[]`](https://forges.link/reference/requests#forgewarning) | Collects the non-fatal warnings of the listing. |
| `query?` | `Record<string, string \| number \| boolean \| undefined>` | Query parameters. Parameters that are `undefined` are left out. Inherited from [`RequestOptions`](https://forges.link/contributing/provider-kit#requestoptions). |
| `select()?` | `(body: unknown, linkNext?: string) => { items: unknown[], next?: string, total?: number }` | Reads items and the next page URL from a response body, for APIs that paginate in the body (Bitbucket's `values` / `next`). Without it, the body is the item array and the next page comes from the `Link` header. `linkNext` is the `Link` header's next URL, for APIs that wrap items in the body but still paginate with `Link`. `total` is the item total the body reports, such as a search's `total_count`. Inherited from [`PaginateOptions`](https://forges.link/contributing/provider-kit#paginateoptions). |
| `mapError()?` | `(error: unknown) => unknown` | Rewrites a failure from this request, for endpoints whose statuses mean something specific. Inherited from [`RequestOptions`](https://forges.link/contributing/provider-kit#requestoptions). |

### `Listing`

One page of `path` as the model, with `options` mapped onto the forge's page-size parameter.

**type:** `<R, T>(path: string, options: PageOptions, map: (raw: R) => T | undefined, extras?: ListingExtras) => Promise<Page<T>>`

### `createListing()`

Builds a [`Listing`](https://forges.link/contributing/provider-kit#listing) for a forge that names its page-size parameter `pageParam`.

```ts
function createListing(fetcher: Fetcher, pageParam: string, defaultPerPage?: number): Listing
```

| Parameter | Type |
| --- | --- |
| `fetcher` | [`Fetcher`](https://forges.link/contributing/provider-kit#fetcher) |
| `pageParam` | `string` |
| `defaultPerPage?` | `number` |

**Returns:** [`Listing`](https://forges.link/contributing/provider-kit#listing)

### `phased()`

Chains listings that a forge serves from separate endpoints. The cursor
`token` records which phase is next, ahead of the phase's own token. With
one phase, the first page is conditional as that phase's is; with more,
one validator cannot cover every endpoint, so no page has an `etag`.

```ts
function phased<T>(phases: Array<(cursor?: Cursor) => Promise<Page<T>>>, cursor?: Cursor): Promise<Page<T>>
```

| Parameter | Type |
| --- | --- |
| `phases` | [`Array<(cursor?: Cursor) => Promise<Page<T>>>`](https://forges.link/reference/requests#cursor) |
| `cursor?` | [`Cursor`](https://forges.link/reference/requests#cursor) |

**Returns:** `Promise<Page<T>>`

### `hasEveryLabel()`

Whether `labels` include every name in `wanted`; true when nothing is wanted.

```ts
function hasEveryLabel(labels: ReadonlyArray<{ name: string }> | undefined, wanted: readonly string[] | undefined): boolean
```

| Parameter | Type |
| --- | --- |
| `labels` | `ReadonlyArray<{ name: string }> \| undefined` |
| `wanted` | `readonly string[] \| undefined` |

**Returns:** `boolean`

### `summariseChecks()`

Any failure fails, else any pending is pending, else any unknown (or none at all) is unknown, else success.

```ts
function summariseChecks(states: CheckState[], url?: string): ChecksSummary
```

| Parameter | Type |
| --- | --- |
| `states` | [`CheckState[]`](https://forges.link/reference/data-model#checkstate) |
| `url?` | `string` |

**Returns:** [`ChecksSummary`](https://forges.link/reference/data-model#checkssummary)

### `memo()`

Caches the result of `load` after its first call. A rejected load is
forgotten so the next call retries; with `ttl` (milliseconds) a resolved
value is reloaded once it is older than that.

```ts
function memo<T>(load: () => Promise<T>, ttl?: number): () => Promise<T>
```

| Parameter | Type |
| --- | --- |
| `load` | `() => Promise<T>` |
| `ttl?` | `number` |

**Returns:** `() => Promise<T>`

### `memoBy()`

[`memo`](https://forges.link/contributing/provider-kit#memo) per key.

```ts
function memoBy<K, T>(load: (key: K) => Promise<T>): (key: K) => Promise<T>
```

| Parameter | Type |
| --- | --- |
| `load` | `(key: K) => Promise<T>` |

**Returns:** `(key: K) => Promise<T>`

### `syntheticReview()`

A review standing in for an approval, vote or participant state on a forge
that has no review objects. `comments` is `false` because there is nothing
to hang inline comments on.

```ts
function syntheticReview(thread: ResolvedThreadRef, id: string, state: ReviewState, extras: { author?: Actor, stateRaw?: string, submittedAt?: Date, raw: unknown }): Review
```

| Parameter | Type |
| --- | --- |
| `thread` | [`ResolvedThreadRef`](https://forges.link/reference/data-model#resolvedthreadref) |
| `id` | `string` |
| `state` | [`ReviewState`](https://forges.link/reference/data-model#reviewstate) |
| `extras` | [`{ author?: Actor, stateRaw?: string, submittedAt?: Date, raw: unknown }`](https://forges.link/reference/data-model#actor) |

**Returns:** [`Review`](https://forges.link/reference/data-model#review)

### `hexColour()`

A label colour as six hex digits, with the `#` prefix the forge expects. `ededed` when none is given.

```ts
function hexColour(colour: string | undefined, prefix: '#' | '' = ''): string
```

| Parameter | Type | Description |
| --- | --- | --- |
| `colour` | `string \| undefined` |  |
| `prefix?` | `'#' \| ''` | Defaults to `''`. |

**Returns:** `string`

### `DEFAULT_REVISION`

The revision that stands for a repository's default branch, and the value `urlFor()` uses
for a file target whose `at` is omitted. Most forges resolve `HEAD` themselves; those that
do not translate it, so the built URL still lands on the default branch.

**type:** `"HEAD"`

### `ReferenceSyntax`

How a forge writes references in Markdown, read back by `parseReferences()`.

| Member | Type | Description |
| --- | --- | --- |
| `threads` | [`ReadonlyArray<{ prefix: string, kind: ThreadKind, number?: string, displayNumber?: boolean, sameRepo?: boolean, namespace?: boolean }>`](https://forges.link/reference/data-model#threadkind) | The prefixes before a thread number, such as `#` or `!`, and the kind of thread each refers to. `number` is the source of a regular expression for the number, digits by default. `displayNumber` marks a prefix whose number is the human-facing one rather than the forge's own identifier, such as Tangled's, so the parsed ref carries `displayNumber`. `sameRepo` marks a prefix that takes no repository, and `namespace` one that refers to the namespace of `from`. |
| `repo?` | `string` | The source of a regular expression for the `owner/name` before a reference to another repository; unset when the forge has none. |
| `suffix?` | `string` | The source of a regular expression for what may follow a thread number, such as GitLab's `+`. |
| `commits?` | `boolean` | Whether a bare sha, and `owner/name@sha` where the forge has `repo`, refer to commits. |

### `WebLinks`

How a provider builds and reads its web URLs. Builders return a path relative
to `baseUrl` or an absolute URL, and may return `undefined` when the forge has no such page.

| Member | Type | Description |
| --- | --- | --- |
| `baseUrl` | `string` | The base URL of the forge website, such as `https://github.com` or `https://example.com/gitlab`. |
| `hosts?` | `readonly string[]` | Other hosts that serve the same pages, such as a domain the forge has moved from. `parse` reads their URLs too. |
| `repo()` | [`(repo: RepoRef) => string`](https://forges.link/reference/data-model#reporef) | The page of a repository. |
| `section()?` | `(repo: RepoRef, section: RepoSection) => string \| undefined` | The page of one of a repository's sections, such as its issues, pull requests, stargazers or forks. |
| `thread()` | [`(ref: ThreadRef) => string \| undefined`](https://forges.link/reference/data-model#threadref) | The page of an issue or pull request. |
| `comment()?` | [`(ref: ResolvedCommentRef) => string \| undefined`](https://forges.link/reference/data-model#resolvedcommentref) | The page of a comment, anchored on its thread. |
| `commit()?` | [`(repo: RepoRef, sha: string) => string \| undefined`](https://forges.link/reference/data-model#reporef) | The page of a commit. |
| `release()?` | [`(ref: ReleaseRef) => string \| undefined`](https://forges.link/reference/data-model#releaseref) | The page of a release. |
| `file()?` | [`(repo: RepoRef, path: string, at: string, line?: number) => string \| undefined`](https://forges.link/reference/data-model#reporef) | The page of a file at a revision, optionally at a line. `HEAD` means the default branch, and a full ref pins a tag or branch by name. |
| `raw()?` | [`(repo: RepoRef, path: string, at: string) => string \| undefined`](https://forges.link/reference/data-model#reporef) | The raw bytes of a file at a revision. `HEAD` means the default branch, and a full ref pins a tag or branch by name. |
| `compare()?` | [`(repo: RepoRef, base: string, head: string) => string \| undefined`](https://forges.link/reference/data-model#reporef) | The page that compares two revisions. |
| `parse()` | `(segments: string[], url: URL, origin: ForgeOrigin) => ParsedForgeUrl \| undefined` | Reads a URL already known to be under `baseUrl`, split into the path segments after it. |
| `reference()?` | `(ref: ThreadRef \| CommitRef, sameRepo: boolean, expand: boolean) => string \| undefined` | The forge's cross-reference syntax; `undefined` falls back to the page URL. |
| `references?` | [`ReferenceSyntax`](https://forges.link/contributing/provider-kit#referencesyntax) | The references that `parseReferences()` reads; unset when the forge has none. |

### `GitHubShape`

How a forge that lays out its website like GitHub differs from GitHub.

| Member | Type | Description |
| --- | --- | --- |
| `pull` | `string` | The path segment of pull requests, such as `pull` or `pulls`. |
| `discussions?` | `boolean` | The forge has discussions, which are addressed like issues. |
| `commentFragment` | `string` | Fragment for a comment id, for example `issuecomment-` or `note_`. |
| `file()` | `(at: string) => string` | The path segment that leads to a file at a revision. |
| `parseFile()?` | `(segments: string[]) => { at: string, path: string } \| undefined` | Reads a file page back from the segments after the repository name; defaults to `blob/{at}/{path}`. |
| `commit?` | `string` | The path segment of commits; defaults to `commit`. |
| `raw?` | `boolean` | Whether the forge serves raw files at `/raw/{at}/{path}`; defaults to `true`. |
| `rawOrigin?` | `string` | The origin that serves raw files at `/{owner}/{name}/{at}/{path}`; when unset, raw files are linked at `/raw/{at}/{path}` on the forge. |
| `lineFragment()` | `(line: number) => string` | The URL fragment that selects a line of a file. |
| `pullPrefix?` | `string` | Reference prefix for pulls when it differs from issues. |
| `sections?` | [`Partial<Record<RepoSection, string \| null>>`](https://forges.link/reference/providers#reposection) | Path segments for sections whose path is not the section's own name, such as a forge that lists stargazers at `stars`; `null` marks a section the forge has no page for, so `section()` returns `undefined` for it. |
| `reserved?` | `readonly string[]` | Reserved owner segments. |
| `references?` | [`ReferenceSyntax`](https://forges.link/contributing/provider-kit#referencesyntax) | The references that `parseReferences()` reads; defaults to `#{n}` and `pullPrefix`, with `owner/name` before them, and commit shas. |

### `githubShapedWeb()`

Web links for forges laid out like GitHub: `/{owner}/{name}/issues/{n}` and friends.

```ts
function githubShapedWeb(baseUrl: string, shape: GitHubShape): WebLinks
```

| Parameter | Type |
| --- | --- |
| `baseUrl` | `string` |
| `shape` | [`GitHubShape`](https://forges.link/contributing/provider-kit#githubshape) |

**Returns:** [`WebLinks`](https://forges.link/contributing/provider-kit#weblinks)

These exports are documented elsewhere: [`ProviderFactoryFunction`](https://forges.link/reference/providers#providerfactoryfunction).


## Sitemap

See the full [sitemap](https://forges.link/sitemap.md) for all pages.
