@gitkraken/core-gitlens 0.10.2 → 0.10.4
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 +15 -1
- package/dist/git/models/pullRequest.d.ts +37 -0
- package/dist/git/models/pullRequest.js.map +1 -1
- package/dist/git-cli/providers/graph.js +14 -8
- package/dist/git-cli/providers/graph.js.map +1 -1
- package/dist/plus/git-github/api/github.d.ts +3 -1
- package/dist/plus/git-github/api/github.js +1 -1
- package/dist/plus/git-github/api/github.js.map +1 -1
- package/dist/plus/integrations/collectionMetadata.d.ts +1 -1
- package/dist/plus/integrations/collectionMetadata.js +19 -8
- package/dist/plus/integrations/collectionMetadata.js.map +1 -1
- package/dist/plus/integrations/errors.d.ts +2 -0
- package/dist/plus/integrations/errors.js +45 -1
- package/dist/plus/integrations/errors.js.map +1 -1
- package/dist/plus/integrations/integrationService.js +2 -2
- package/dist/plus/integrations/integrationService.js.map +1 -1
- package/dist/plus/integrations/models/gitHostIntegration.d.ts +5 -1
- package/dist/plus/integrations/models/gitHostIntegration.js.map +1 -1
- package/dist/plus/integrations/models/integration.d.ts +1 -0
- package/dist/plus/integrations/models/integration.js +7 -4
- package/dist/plus/integrations/models/integration.js.map +1 -1
- package/dist/plus/integrations/providers/azure/azure.js +2 -6
- package/dist/plus/integrations/providers/azure/azure.js.map +1 -1
- package/dist/plus/integrations/providers/azureDevOps.d.ts +1 -2
- package/dist/plus/integrations/providers/azureDevOps.js +12 -5
- package/dist/plus/integrations/providers/azureDevOps.js.map +1 -1
- package/dist/plus/integrations/providers/azureDevOpsServer.js.map +1 -1
- package/dist/plus/integrations/providers/bitbucket.js +2 -1
- package/dist/plus/integrations/providers/bitbucket.js.map +1 -1
- package/dist/plus/integrations/providers/github.d.ts +12 -1
- package/dist/plus/integrations/providers/github.js +42 -2
- package/dist/plus/integrations/providers/github.js.map +1 -1
- package/dist/plus/integrations/providers/gitlab.d.ts +1 -1
- package/dist/plus/integrations/providers/gitlab.js +3 -2
- package/dist/plus/integrations/providers/gitlab.js.map +1 -1
- package/dist/plus/integrations/providers/models.js +1 -0
- package/dist/plus/integrations/providers/models.js.map +1 -1
- package/dist/plus/integrations/results.d.ts +8 -5
- package/dist/plus/integrations/results.js +3 -1
- package/dist/plus/integrations/results.js.map +1 -1
- package/dist/utils/cancellation.d.ts +2 -3
- package/dist/utils/cancellation.js +2 -3
- package/dist/utils/cancellation.js.map +1 -1
- package/package.json +2 -2
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { AuthenticationError, RequestNotFoundError, RequestRateLimitError } from "../../git/errors.js";
|
|
2
|
+
import { isProviderUnreachableError } from "./errors.js";
|
|
2
3
|
import { isUnsupportedSortError } from "@gitkraken/provider-apis";
|
|
3
4
|
//#region ../plus/integrations/src/results.ts
|
|
4
5
|
const maxProviderWarningMessageLength = 500;
|
|
@@ -29,7 +30,8 @@ function toProviderWarning(providerId, domain, connectionId, ex) {
|
|
|
29
30
|
connectionId,
|
|
30
31
|
message: providerWarningMessage(ex),
|
|
31
32
|
kind,
|
|
32
|
-
isAuth: kind === "auth"
|
|
33
|
+
isAuth: kind === "auth",
|
|
34
|
+
...kind === "other" && isProviderUnreachableError(ex) ? { cause: { reason: "unreachable" } } : {}
|
|
33
35
|
};
|
|
34
36
|
}
|
|
35
37
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"results.js","names":[],"sources":["../../../../plus/integrations/src/results.ts"],"sourcesContent":["import { isUnsupportedSortError } from '@gitkraken/provider-apis';\nimport { AuthenticationError, RequestNotFoundError, RequestRateLimitError } from '@gitlens/git/errors.js';\nimport type { IssueSorting } from '@gitlens/git/models/issue.js';\nimport type { PullRequestSorting } from '@gitlens/git/models/pullRequest.js';\nimport type { IntegrationIds } from './constants.js';\n\nexport interface ConnectionStateChangeEvent {\n\tkey: string;\n\treason: 'connected' | 'disconnected';\n}\n\n/**\n * A per-provider, per-connection warning surfaced alongside (partial) read results. Consumers use\n * these to drive auth recovery, retry, or truncation messaging without the read itself throwing.\n *\n * `kind` is the programmatic discriminant (a rate-limit is retryable, a 404 is not, an unsupported capability\n * never succeeds on retry, an auth failure needs re-connection unless {@link ProviderWarning.scope} confines\n * it); `isAuth` is retained as a convenience mirror of `kind === 'auth'`.\n *\n * `'unsupported'`: the provider — or this integration of it — lacks the capability the request asked for: a\n * surface (issues on Bitbucket, pull requests on an issue tracker, a batch read, org/repo discovery,\n * current-account lookup, project-scoped or account-wide issue reads), or a filter, sort, state, search\n * criterion or option combination it cannot express. Retrying the same request never succeeds; a different\n * provider, scope or request may. NOT unsupported (these stay `'other'`): malformed or contradictory caller\n * input the caller fixes in the request itself (a duplicate batch key, invalid target numbers, an empty owner,\n * an unusable scope), incompleteness or omission warnings, and unclassified errors.\n */\nexport type ProviderWarningKind = 'auth' | 'rate-limit' | 'not-found' | 'no-connection' | 'unsupported' | 'other';\n\n/**\n * Why a read that SUCCEEDED still withheld results:\n * - `provider-limit`: the provider refuses to serve past a cap it enforces (GitHub search's 1,000-result\n * ceiling, Trello's `cards_limit`), so the excess is unreachable through that query.\n * - `recovery-budget`: the internal partitioned recovery stopped spending upstream requests before it ran\n * out of partitions to visit.\n * - `pagination-incomplete`: pages were left unread — a sub-scope of a multi-scope read that was not drained,\n * a drain that stopped at its own page backstop, or a provider that advertised another page and gave no way\n * to reach it. These have DIFFERENT remedies, so the kind alone does not say whether more can be fetched;\n * read {@link ProviderWarningOmission.recovery} for that.\n *\n * Mirrors the vocabulary the SDK reports. Declared here rather than imported so this module stays free of\n * `@gitkraken/provider-apis` types (see the export block in `index.ts`); `collectionMetadata.ts` holds the\n * compile-time link, so an SDK bump that adds a kind fails the build at that boundary.\n */\nexport type ProviderWarningOmissionKind = 'provider-limit' | 'recovery-budget' | 'pagination-incomplete';\n\n/**\n * How a consumer can recover omitted results. `page-budget` reruns with a larger budget; `narrow-scope`\n * requests a smaller server-side scope; `none` promises neither. Switch on the exact value because only\n * `page-budget` is a fetch-more action.\n */\nexport type ProviderWarningOmissionRecovery = 'none' | 'page-budget' | 'narrow-scope';\n\n/**\n * The part of a provider a warning is confined to: one resource (organization, workspace, site), project or\n * repository. All fields optional; see {@link ProviderWarning.scope} for when one is forwarded.\n */\nexport interface ProviderWarningScope {\n\t/**\n\t * The resource as the read addressed it: its id on most reads, its name on the few that address it by name\n\t * (Azure DevOps' repo-scoped reads, Bitbucket's workspace reads). Match it against both\n\t * `ProviderOrganization.id` and `name`.\n\t */\n\tresourceId?: string;\n\tprojectId?: string;\n\trepositoryId?: string;\n}\n\n/**\n * Why a provider refused a credential it otherwise accepts, when the refusal itself says so:\n * - `oauth-app-not-allowed`: the organization does not let third-party OAuth apps in. On Azure DevOps this is the\n * organization policy \"Third-party application access via OAuth\", off by default for new organizations. An\n * organization admin enables it, or the user connects with a personal access token instead, which the policy\n * does not govern.\n * - `access-denied`: the account has no access to that organization or project (not a member, or lacking the\n * permission). Someone who administers it has to grant access.\n * - `conditional-access`: a Microsoft Entra Conditional Access policy blocked the request (Azure DevOps\n * `VS403463`). Its admin has to exempt the request, e.g. by location or device.\n *\n * None of these is healed by reconnecting, which is the point of naming them.\n */\nexport type ProviderWarningCauseReason = 'oauth-app-not-allowed' | 'access-denied' | 'conditional-access';\n\n/** See {@link ProviderWarning.cause}. */\nexport interface ProviderWarningCause {\n\treason: ProviderWarningCauseReason;\n\t/** The provider's own error code, when it reports one (Azure DevOps `TF400813`, `VS403463`). */\n\tcode?: string;\n\t/** Where the setting behind the refusal is changed, when this layer can address it. */\n\tremedyUrl?: string;\n}\n\n/** Which repository / project / resource an omission is attributed to. All fields optional; a scope may name none. */\nexport interface ProviderWarningOmissionScope extends ProviderWarningScope {\n\tproviderId?: string;\n}\n\nexport interface ProviderWarningOmission {\n\tkind: ProviderWarningOmissionKind;\n\t/**\n\t * Whether anything would fetch the missing items, and what. Gate a \"load more\" affordance on this rather\n\t * than on `kind` — see {@link ProviderWarningOmissionRecovery}.\n\t */\n\trecovery: ProviderWarningOmissionRecovery;\n\t/**\n\t * The cap the provider enforces, when it reports one. NOT a result count for every kind: on\n\t * `recovery-budget` this is a REQUEST budget and must not be shown to a user as a number of results.\n\t */\n\tlimit?: number;\n\t/** Total matches the provider reported, when it reports one. Only GitHub's search cap does today. */\n\ttotalCount?: number;\n\t/**\n\t * The order the reachable window was selected under, as `field:direction`, when the omission is a result\n\t * ceiling.\n\t *\n\t * Present so a consumer can word its own \"N matched, showing the first M\" without assuming WHICH M: the\n\t * provider serves the top M under this key, so the sentence is only true if it names it. Absent for every\n\t * omission that isn't a ceiling, where no window was selected by an order.\n\t *\n\t * A union of both vocabularies rather than the issue one alone: `PullRequestSorting` happens to be a subset\n\t * today, so narrowing this to {@link IssueSorting} would still compile while describing only half the reads\n\t * that set it — and would break the day the PR search gains a key the issue search has no name for.\n\t */\n\tsort?: IssueSorting | PullRequestSorting;\n\t/** Which repository / project / resource was affected, when one is attributed. */\n\tscope?: ProviderWarningOmissionScope;\n}\n\nexport interface ProviderWarning {\n\tproviderId: IntegrationIds;\n\t/** Disambiguates connections on self-managed hosts (where one provider id spans multiple domains). */\n\tdomain?: string;\n\t/** The specific token/connection the read was pinned to, when a `connectionId` was supplied. */\n\tconnectionId?: string;\n\tmessage: string;\n\tkind: ProviderWarningKind;\n\t/** Convenience mirror of `kind === 'auth'`, scoped or not; read {@link scope} before prompting to reconnect. */\n\tisAuth: boolean;\n\t/**\n\t * Present when the failure was recorded against one sub-scope of the read (an organization, project or\n\t * repository) rather than against the connection. A scoped `auth` failure is that one scope refusing this\n\t * credential, e.g. an Azure DevOps organization that disallows third-party OAuth apps, one in another Entra\n\t * tenant, or a Conditional Access policy. Reconnecting cannot fix those, so this warning alone is no reason\n\t * to prompt for it.\n\t *\n\t * `kind` and `isAuth` are unaffected: a scoped 401 is still an authentication failure, and this field says\n\t * how far it reaches. It names at least one of its IDs, and is never set on an omission (which carries its\n\t * own {@link ProviderWarningOmission.scope}) or on a warning derived from a caught exception (see\n\t * {@link toProviderWarning}), even when that call targeted a single organization. The exception is a batch\n\t * read's refused target, which names its scope: the Azure DevOps organization and project, the repository on\n\t * other git hosts, or the tracker's resource.\n\t *\n\t * Its ABSENCE means account-wide or unattributed, so existing handling stays correct without it.\n\t *\n\t * A scoped `auth` failure also means the credential itself was accepted. A dead token can come back as nothing\n\t * but scoped refusals wherever a read reaches its scopes without an uncached request to the connection first:\n\t * discovery served from a per-token cache (Azure DevOps, Bitbucket, Jira Cloud) or an SDK fan-out across the\n\t * requested repositories (Bitbucket Data Center). So when a read's only auth failures are scoped, those providers\n\t * confirm the credential with one uncached check first, and a refused credential fails the whole read with an\n\t * unscoped `auth` warning. A batch read checks it only when every target was refused, since a target that\n\t * answered already proved it. A refusal the provider attributes to the credential itself, like Bitbucket's or Jira\n\t * Cloud's for a token missing the OAuth scopes a read needs, which a reconnect fixes, is published unscoped too,\n\t * once for the connection, while the scopes that answered keep their results.\n\t *\n\t * So the promise holds for a read that carries no unscoped `auth` warning of its own; one that does already asks\n\t * for a reconnect, and its other scoped refusals are not checked. Two exceptions stay scoped even then. A check\n\t * that could not complete or was denied (a network error, a throttle, a `403`, Bitbucket Data Center refusing a\n\t * credential it authenticated, or a Bitbucket Data Center project access token, whose user the check cannot\n\t * find) proves nothing, so the warnings are published unconfirmed, with no {@link cause}, and the next read\n\t * checks again. And a credential confirmed within the last minute is not probed again, so a revocation can take\n\t * up to a minute to surface.\n\t */\n\tscope?: ProviderWarningScope;\n\t/**\n\t * Why the provider refused, when the refusal itself says so: see {@link ProviderWarningCauseReason}. Switch on\n\t * `reason` to recommend a fix instead of a reconnect; `message` then carries the same explanation as prose.\n\t *\n\t * Set only on a scoped `auth` warning whose credential was confirmed first (see {@link scope}), because the\n\t * refusals it names are indistinguishable from a dead credential until then: Azure DevOps answers a\n\t * third-party OAuth app its organization disallows exactly as it answers an expired token. Only Azure DevOps\n\t * reports one today. Its absence proves nothing about the cause.\n\t */\n\tcause?: ProviderWarningCause;\n\t/**\n\t * Present when this warning describes results the read could not return even though the request itself\n\t * SUCCEEDED — a provider-enforced cap, an exhausted recovery budget, a page budget, or a sub-scope the read\n\t * did not drain.\n\t *\n\t * Its presence is the signal: an omission is not a failure. Message it as incompleteness rather than as a\n\t * failed read, and do NOT derive that from `message`, which is English prose and subject to rewording.\n\t * `kind` stays `'other'` for these, so the failure discriminant keeps meaning exactly what it meant before\n\t * this field existed.\n\t *\n\t * Whether anything would fetch the rest is a SEPARATE question — read {@link ProviderWarningOmission.recovery},\n\t * not `kind`, and never assume a retry of the same request returns more.\n\t *\n\t * `limit` / `totalCount` / `scope` are forwarded only when they are reported; most omissions carry none of\n\t * the three, so render correctly without them — and see {@link ProviderWarningOmission.limit} before\n\t * showing that figure as a result count.\n\t *\n\t * Its ABSENCE proves nothing. It is never set on a warning derived from a caught exception (see\n\t * {@link toProviderWarning}) or from a structured scope failure — those are failures, and the field would\n\t * be a lie there. But it is also absent whenever incompleteness was reported without naming what was left\n\t * out, so treat a bare `kind: 'other'` warning as unclassified rather than as a proven failure.\n\t */\n\tomission?: ProviderWarningOmission;\n}\n\nexport interface ProviderPageInfo {\n\t/**\n\t * The 1-based POSITION of the returned page. One convention across every paged read, page-number and\n\t * cursor paging alike, so a `getNextPageParam`-style consumer can key off it uniformly:\n\t * - the page number the provider itself reported, when it reports one (authoritative);\n\t * - else the position the caller addressed: the page encoded in a threaded page cursor, or the `page`\n\t * supplied alongside an opaque cursor (1 when the caller supplied no `page`);\n\t * - else, for a read that can be advanced by page number, the requested `page` — the provider either\n\t * honored it or the internal drain reached it (see the paging contract on `IntegrationManager`);\n\t * - else 1: a cursor-only read with no cursor threaded back ignores a requested page number and answers\n\t * with its first page, so echoing the request would mislabel page 1 as page N.\n\t *\n\t * A page past the provider's terminal cursor still reports the requested `page` with empty `items` — an\n\t * empty page N, never page N-1 relabeled.\n\t *\n\t * Continue a cursor-paged read from `cursor`, NOT from `currentPage + 1`: a cursor-only host can't be\n\t * addressed by number, so this is a position label and not always a resumable request parameter.\n\t */\n\tcurrentPage: number;\n\t/**\n\t * The page size IN EFFECT, which is not always the one requested — it is whichever of these the read can\n\t * actually vouch for:\n\t * - the size the provider reported for the page it served (numbered-page hosts), else\n\t * - the `itemsPerPage` that was applied to the request (repo-scoped reads, which forward it), else\n\t * - `items.length`, for a read that takes no page size at all: the account-wide PR/issue reads, `listRepos`\n\t * (cursor-only), and `listIssueTrackerIssuesPage`, whose `itemsPerPage` counts PROJECTS rather than issues.\n\t *\n\t * So it is a description of the page, not an echo of the request: don't derive a total from\n\t * `currentPage * itemsPerPage`, and don't read `items.length < itemsPerPage` as \"last page\" — `hasMore` /\n\t * `cursor` are the only continuation signals.\n\t */\n\titemsPerPage: number;\n\t/**\n\t * A COMPLETENESS assertion, not a mode flag: `true` only when a sweep drained every page of every target\n\t * without truncating or failing (`!truncated && !fetchFailed`). Set exclusively by `sweepPullRequests` /\n\t * `sweepClosedPullRequests` and absent on every paged read, so `allPages !== true` does NOT by itself mean\n\t * \"this was a single page\".\n\t *\n\t * This is the signal to gate on before caching a sweep as authoritative: unlike `truncated` it is `false`\n\t * for BOTH kinds of incompleteness, so it can't be misread as a benign cap.\n\t */\n\tallPages?: boolean;\n\t/**\n\t * True when the read stopped before it could confirm it had everything. Deliberately does NOT distinguish\n\t * WHY, and a consumer must not assume it means a provider ceiling — a sweep sets it from three different\n\t * origins:\n\t * - a provider-side ceiling or per-scope backstop propagated from below (e.g. GitHub Search's 1000-result\n\t * cap): the missing items are NOT reachable, so this really is \"complete to the provider's limit\";\n\t * - the sweep's OWN `maxPages` cap (default 100) with a usable cursor still in hand: the missing items ARE\n\t * reachable and were simply not fetched — raise `maxPages` to get them;\n\t * - the provider reporting another page but handing back no usable cursor: not reachable.\n\t *\n\t * Only the second is recoverable, and a sweep exposes no continuation cursor, so treating a truncated sweep\n\t * as a complete set silently drops reachable data in that case. Prefer `allPages` for the cache decision.\n\t */\n\ttruncated?: boolean;\n}\n\nexport interface ProviderResult<T> {\n\titems: T[];\n\twarnings: ProviderWarning[];\n\t/**\n\t * True when `items` is incomplete — distinguishes a failed or truncated flat read from a genuinely empty\n\t * result. Paged results additionally use `page.truncated` when a completed page could not confirm it\n\t * drained everything.\n\t */\n\tfetchFailed?: boolean;\n}\n\nexport interface ProviderPagedResult<T> extends ProviderResult<T> {\n\tpage: ProviderPageInfo;\n\thasMore: boolean;\n\t/**\n\t * Opaque cursor for cursor-based paging (GraphQL, per-repo/per-project cursors, etc.). For hosts that\n\t * require the previous page's cursor, consumers should pass this value back to the next `cursor` option.\n\t * A retry-only cursor may remain when `hasMore` is false: `hasMore` means automatic forward progress,\n\t * while explicitly reusing such a cursor retries failed work without creating an infinite paging loop.\n\t */\n\tcursor?: string;\n}\n\nexport interface ProviderSweepResult<T> extends ProviderResult<T> {\n\tpage: ProviderPageInfo;\n\thasMore: boolean;\n\t/**\n\t * Providers whose top-level read failed before returning any usable page. Partial per-scope failures stay\n\t * represented by `warnings` + `fetchFailed` and are intentionally excluded.\n\t */\n\tfailedProviderIds: IntegrationIds[];\n\t/**\n\t * Providers whose read started successfully but could not produce an authoritative complete slice (for\n\t * example, a later page failed, collection metadata reported a partial scope, or a paging backstop was hit).\n\t * Kept separate from\n\t * `failedProviderIds` so consumers can accept healthy sibling providers while preserving an older snapshot\n\t * for a provider whose returned slice has a gap.\n\t */\n\tincompleteProviderIds: IntegrationIds[];\n}\n\nexport interface ProviderBroadenResult<T> extends ProviderPagedResult<T> {\n\tbroadenedProviderIds: IntegrationIds[];\n\t/** Providers for which no requested org produced a usable issue result. */\n\tfailedProviderIds: IntegrationIds[];\n\t/** Providers with both a usable org result and at least one failed or truncated org slice. */\n\tincompleteProviderIds: IntegrationIds[];\n\tfanOutCount: number;\n}\n\nexport type RepositoryResolutionStatus =\n\t| 'resolved'\n\t| 'not-found'\n\t| 'unauthorized'\n\t| 'unsupported-provider'\n\t| 'invalid-remote-url'\n\t| 'host-mismatch'\n\t| 'undetermined';\n\nexport interface RepositoryIdentity {\n\tproviderId: IntegrationIds;\n\tdomain: string;\n\t/** The provider's canonical owner/namespace (follows renames), falling back to the parsed remote when omitted. */\n\towner: string;\n\t/** The provider's canonical repo name (follows renames), falling back to the parsed remote when omitted. */\n\tname: string;\n\tproject?: string;\n\t/** The original input remote URL, so the caller can key the resolution back to the remote it asked about. */\n\tremoteUrl: string;\n\t/**\n\t * True when the provider's canonical owner/name differ from what the input remote URL carried — i.e. the\n\t * repo was renamed/moved host-side and the local remote is stale. Case-insensitive, mirroring gkcli's\n\t * `EqualFold` compare so hosts that echo the input casing (e.g. Bitbucket Server/Azure) aren't flagged.\n\t */\n\trenamed: boolean;\n}\n\nexport interface RepositoryResolution {\n\tstatus: RepositoryResolutionStatus;\n\tidentity?: RepositoryIdentity;\n\twarning?: ProviderWarning;\n}\n\nexport interface ResolveRepositoryResult {\n\tresolution: RepositoryResolution;\n}\n\nconst maxProviderWarningMessageLength = 500;\n\n/** A caught error's message as a warning can carry it: an HTML page becomes its status, and prose is capped. */\nexport function providerWarningMessage(ex: unknown): string {\n\tconst raw = (ex instanceof Error ? ex.message : String(ex)).trim();\n\tconst carrier = ex as { status?: unknown; response?: { status?: unknown } } | null | undefined;\n\tconst status =\n\t\ttypeof carrier?.status === 'number'\n\t\t\t? carrier.status\n\t\t\t: typeof carrier?.response?.status === 'number'\n\t\t\t\t? carrier.response.status\n\t\t\t\t: undefined;\n\n\t// Gateways commonly answer API requests with a complete HTML error page. That payload is neither actionable\n\t// nor suitable for a warning DTO consumed by UIs and logs; preserve the status without leaking the document.\n\tif (/<(?:!doctype\\s+html|html|head|body)\\b/i.test(raw)) {\n\t\treturn status != null ? `Provider request failed with status ${status}.` : 'Provider request failed.';\n\t}\n\n\tif (!raw) {\n\t\treturn status != null ? `Provider request failed with status ${status}.` : 'Provider request failed.';\n\t}\n\treturn raw.length > maxProviderWarningMessageLength\n\t\t? `${raw.slice(0, maxProviderWarningMessageLength - 3)}...`\n\t\t: raw;\n}\n\n/**\n * Normalized org/workspace/group shape returned by the provider facade.\n * `name` is the provider identifier to pass to follow-up reads, while `org` is an optional display label.\n */\nexport interface ProviderOrganization {\n\tid: string;\n\tproviderId: IntegrationIds;\n\tname: string;\n\torg?: string;\n\turl: string;\n}\n\n/** Normalized repository shape returned by the provider facade. */\nexport interface ProviderRepositoryShape {\n\tid: string;\n\tnamespace: string;\n\tname: string;\n\t/** Azure DevOps project; `undefined` for hosts without a project layer. */\n\tproject?: string;\n\t/** Web (browser) URL, when the provider exposes it. */\n\turl?: string;\n\t/** HTTPS clone URL, when available. */\n\tcloneUrlHttps?: string;\n\t/** SSH clone URL, when available. */\n\tcloneUrlSsh?: string;\n\t/** Default branch name, when the provider reports it. */\n\tdefaultBranch?: string;\n}\n\n/**\n * Classifies a caught provider exception into a neutral {@link ProviderWarning}. Ordering matters:\n * `instanceof` is checked most-specific-first so a rate-limit isn't mislabeled as a generic error and\n * a 404 isn't mislabeled as auth.\n */\nexport function toProviderWarning(\n\tproviderId: IntegrationIds,\n\tdomain: string | undefined,\n\tconnectionId: string | undefined,\n\tex: unknown,\n): ProviderWarning {\n\tlet kind: ProviderWarning['kind'];\n\tif (ex instanceof AuthenticationError) {\n\t\tkind = 'auth';\n\t} else if (ex instanceof RequestRateLimitError) {\n\t\tkind = 'rate-limit';\n\t} else if (ex instanceof RequestNotFoundError) {\n\t\tkind = 'not-found';\n\t} else if (isUnsupportedSortError(ex)) {\n\t\tkind = 'unsupported';\n\t} else {\n\t\tkind = 'other';\n\t}\n\n\treturn {\n\t\tproviderId: providerId,\n\t\tdomain: domain,\n\t\tconnectionId: connectionId,\n\t\tmessage: providerWarningMessage(ex),\n\t\tkind: kind,\n\t\tisAuth: kind === 'auth',\n\t};\n}\n\n/**\n * A scope's identity, as the stable string that keys it.\n *\n * The single definition of what \"the same scope\" means, shared by the failure and omission dedup keys in\n * `providerPaging.ts` and by {@link providerWarningKey} below, so a scope gaining a field is one edit rather\n * than three. `providerId` is included: the same repository ID under two providers is two scopes.\n *\n * The parameter is structural rather than the SDK's `CollectionScope` so this module keeps naming no\n * `@gitkraken/provider-apis` types (see the export block in `index.ts`) while still serving its SDK-facing\n * callers, which pass that type in unchanged.\n */\nexport function collectionScopeKey(scope: ProviderWarningOmissionScope | undefined): string {\n\treturn [scope?.providerId ?? '', scope?.resourceId ?? '', scope?.projectId ?? '', scope?.repositoryId ?? ''].join(\n\t\t' ',\n\t);\n}\n\n/**\n * The omission's contribution to a warning's identity — empty when there is none, so a warning without an\n * omission keeps deduping exactly as it did before the field existed.\n *\n * Two omissions of different kinds do produce different `message` values today, so message alone would still\n * separate them. That is incidental: the premise of `omission` is that consumers must not depend on prose\n * carrying the distinguishing fact, and this key must not either.\n */\nfunction providerWarningOmissionKey(omission: ProviderWarningOmission | undefined): string {\n\tif (omission == null) return '';\n\n\treturn [\n\t\tomission.kind,\n\t\tomission.recovery,\n\t\tomission.limit ?? '',\n\t\tomission.totalCount ?? '',\n\t\tcollectionScopeKey(omission.scope),\n\t].join(' ');\n}\n\n/**\n * Strips the omission from every warning in `warnings` when the read as a whole failed.\n *\n * An omission asserts the request SUCCEEDED, and a drain only learns it failed AFTER it may have emitted one:\n * an early page can report its own truncation and then a later page can die. Deciding per warning, at the\n * moment each is built, cannot see that future — so the aggregate is reconciled once, here, where\n * `fetchFailed` is final. Call it at the point a read returns its `fetchFailed`.\n *\n * Re-dedupes as it goes: the omission is part of a warning's identity, so two warnings that differed only\n * there become identical once it is gone, and the array's contract is that no two entries are equal.\n *\n * Mutates in place: the warning array is the one being returned, and callers accumulate into it across pages.\n */\nexport function reconcileOmissionsWithFailure(warnings: ProviderWarning[], fetchFailed: boolean): void {\n\tif (!fetchFailed || !warnings.some(w => w.omission != null)) return;\n\n\tconst reconciled: ProviderWarning[] = [];\n\tfor (const warning of warnings) {\n\t\tif (warning.omission == null) {\n\t\t\tappendDedupedWarning(reconciled, warning);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst { omission: _omission, ...rest } = warning;\n\t\tappendDedupedWarning(reconciled, rest);\n\t}\n\n\twarnings.splice(0, warnings.length, ...reconciled);\n}\n\n/**\n * A stable key for deduplicating warnings accumulated across drained pages / fan-out scopes.\n *\n * The scope and the cause are keyed for the reason the omission is (see {@link providerWarningOmissionKey}): today's\n * failure messages happen to spell them out, but two failures that differ in either must stay two warnings even if\n * they don't.\n *\n * `message` stays LAST. It is the only free-form segment — provider prose, spaces and all — so anything\n * appended after it could be impersonated by a message that happens to end in the same text.\n */\nfunction providerWarningKey(warning: ProviderWarning): string {\n\treturn [\n\t\twarning.providerId,\n\t\twarning.connectionId ?? '',\n\t\twarning.domain ?? '',\n\t\twarning.kind,\n\t\tcollectionScopeKey(warning.scope),\n\t\twarning.cause?.reason ?? '',\n\t\tproviderWarningOmissionKey(warning.omission),\n\t\twarning.message,\n\t].join(' ');\n}\n\n/**\n * Appends `warning` to `into` only when an equal warning (by provider/connection/domain/kind/message, plus the\n * structured scope, cause and omission when present) is absent.\n */\nexport function appendDedupedWarning(into: ProviderWarning[], warning: ProviderWarning): void {\n\tconst key = providerWarningKey(warning);\n\tif (into.some(existing => providerWarningKey(existing) === key)) return;\n\n\tinto.push(warning);\n}\n"],"mappings":";;;AAiWA,MAAM,kCAAkC;;AAGxC,SAAgB,uBAAuB,IAAqB;CAC3D,MAAM,OAAO,cAAc,QAAQ,GAAG,UAAU,OAAO,EAAE,EAAA,CAAG,KAAK;CACjE,MAAM,UAAU;CAChB,MAAM,SACL,OAAO,SAAS,WAAW,WACxB,QAAQ,SACR,OAAO,SAAS,UAAU,WAAW,WACpC,QAAQ,SAAS,SACjB,KAAA;CAIL,IAAI,yCAAyC,KAAK,GAAG,GACpD,OAAO,UAAU,OAAO,uCAAuC,OAAO,KAAK;CAG5E,IAAI,CAAC,KACJ,OAAO,UAAU,OAAO,uCAAuC,OAAO,KAAK;CAE5E,OAAO,IAAI,SAAS,kCACjB,GAAG,IAAI,MAAM,GAAG,GAAmC,EAAE,OACrD;AACJ;;;;;;AAoCA,SAAgB,kBACf,YACA,QACA,cACA,IACkB;CAClB,IAAI;CACJ,IAAI,cAAc,qBACjB,OAAO;MACD,IAAI,cAAc,uBACxB,OAAO;MACD,IAAI,cAAc,sBACxB,OAAO;MACD,IAAI,uBAAuB,EAAE,GACnC,OAAO;MAEP,OAAO;CAGR,OAAO;EACM;EACJ;EACM;EACd,SAAS,uBAAuB,EAAE;EAC5B;EACN,QAAQ,SAAS;CAClB;AACD;;;;;;;;;;;;AAaA,SAAgB,mBAAmB,OAAyD;CAC3F,OAAO;EAAC,OAAO,cAAc;EAAI,OAAO,cAAc;EAAI,OAAO,aAAa;EAAI,OAAO,gBAAgB;CAAE,CAAC,CAAC,KAC5G,GACD;AACD;;;;;;;;;AAUA,SAAS,2BAA2B,UAAuD;CAC1F,IAAI,YAAY,MAAM,OAAO;CAE7B,OAAO;EACN,SAAS;EACT,SAAS;EACT,SAAS,SAAS;EAClB,SAAS,cAAc;EACvB,mBAAmB,SAAS,KAAK;CAClC,CAAC,CAAC,KAAK,GAAG;AACX;;;;;;;;;;;;;;AAeA,SAAgB,8BAA8B,UAA6B,aAA4B;CACtG,IAAI,CAAC,eAAe,CAAC,SAAS,MAAK,MAAK,EAAE,YAAY,IAAI,GAAG;CAE7D,MAAM,aAAgC,CAAC;CACvC,KAAK,MAAM,WAAW,UAAU;EAC/B,IAAI,QAAQ,YAAY,MAAM;GAC7B,qBAAqB,YAAY,OAAO;GACxC;EACD;EAEA,MAAM,EAAE,UAAU,WAAW,GAAG,SAAS;EACzC,qBAAqB,YAAY,IAAI;CACtC;CAEA,SAAS,OAAO,GAAG,SAAS,QAAQ,GAAG,UAAU;AAClD;;;;;;;;;;;AAYA,SAAS,mBAAmB,SAAkC;CAC7D,OAAO;EACN,QAAQ;EACR,QAAQ,gBAAgB;EACxB,QAAQ,UAAU;EAClB,QAAQ;EACR,mBAAmB,QAAQ,KAAK;EAChC,QAAQ,OAAO,UAAU;EACzB,2BAA2B,QAAQ,QAAQ;EAC3C,QAAQ;CACT,CAAC,CAAC,KAAK,GAAG;AACX;;;;;AAMA,SAAgB,qBAAqB,MAAyB,SAAgC;CAC7F,MAAM,MAAM,mBAAmB,OAAO;CACtC,IAAI,KAAK,MAAK,aAAY,mBAAmB,QAAQ,MAAM,GAAG,GAAG;CAEjE,KAAK,KAAK,OAAO;AAClB"}
|
|
1
|
+
{"version":3,"file":"results.js","names":[],"sources":["../../../../plus/integrations/src/results.ts"],"sourcesContent":["import { isUnsupportedSortError } from '@gitkraken/provider-apis';\nimport { AuthenticationError, RequestNotFoundError, RequestRateLimitError } from '@gitlens/git/errors.js';\nimport type { IssueSorting } from '@gitlens/git/models/issue.js';\nimport type { PullRequestSorting } from '@gitlens/git/models/pullRequest.js';\nimport type { IntegrationIds } from './constants.js';\nimport { isProviderUnreachableError } from './errors.js';\n\nexport interface ConnectionStateChangeEvent {\n\tkey: string;\n\treason: 'connected' | 'disconnected';\n}\n\n/**\n * A per-provider, per-connection warning surfaced alongside (partial) read results. Consumers use\n * these to drive auth recovery, retry, or truncation messaging without the read itself throwing.\n *\n * `kind` is the programmatic discriminant (a rate-limit is retryable, a 404 is not, an unsupported capability\n * never succeeds on retry, an auth failure needs re-connection unless {@link ProviderWarning.scope} confines\n * it); `isAuth` is retained as a convenience mirror of `kind === 'auth'`.\n *\n * `'unsupported'`: the provider — or this integration of it — lacks the capability the request asked for: a\n * surface (issues on Bitbucket, pull requests on an issue tracker, a batch read, org/repo discovery,\n * current-account lookup, project-scoped or account-wide issue reads), or a filter, sort, state, search\n * criterion or option combination it cannot express. Retrying the same request never succeeds; a different\n * provider, scope or request may. NOT unsupported (these stay `'other'`): malformed or contradictory caller\n * input the caller fixes in the request itself (a duplicate batch key, invalid target numbers, an empty owner,\n * an unusable scope), incompleteness or omission warnings, and unclassified errors.\n */\nexport type ProviderWarningKind = 'auth' | 'rate-limit' | 'not-found' | 'no-connection' | 'unsupported' | 'other';\n\n/**\n * Why a read that SUCCEEDED still withheld results:\n * - `provider-limit`: the provider refuses to serve past a cap it enforces (GitHub search's 1,000-result\n * ceiling, Trello's `cards_limit`), so the excess is unreachable through that query.\n * - `recovery-budget`: the internal partitioned recovery stopped spending upstream requests before it ran\n * out of partitions to visit.\n * - `pagination-incomplete`: pages were left unread — a sub-scope of a multi-scope read that was not drained,\n * a drain that stopped at its own page backstop, or a provider that advertised another page and gave no way\n * to reach it. These have DIFFERENT remedies, so the kind alone does not say whether more can be fetched;\n * read {@link ProviderWarningOmission.recovery} for that.\n *\n * Mirrors the vocabulary the SDK reports. Declared here rather than imported so this module stays free of\n * `@gitkraken/provider-apis` types (see the export block in `index.ts`); `collectionMetadata.ts` holds the\n * compile-time link, so an SDK bump that adds a kind fails the build at that boundary.\n */\nexport type ProviderWarningOmissionKind = 'provider-limit' | 'recovery-budget' | 'pagination-incomplete';\n\n/**\n * How a consumer can recover omitted results. `page-budget` reruns with a larger budget; `narrow-scope`\n * requests a smaller server-side scope; `none` promises neither. Switch on the exact value because only\n * `page-budget` is a fetch-more action.\n */\nexport type ProviderWarningOmissionRecovery = 'none' | 'page-budget' | 'narrow-scope';\n\n/**\n * The part of a provider a warning is confined to: one resource (organization, workspace, site), project or\n * repository. All fields optional; see {@link ProviderWarning.scope} for when one is forwarded.\n */\nexport interface ProviderWarningScope {\n\t/**\n\t * The resource as the read addressed it: its id on most reads, its name on the few that address it by name\n\t * (Azure DevOps' repo-scoped reads, Bitbucket's workspace reads). Match it against both\n\t * `ProviderOrganization.id` and `name`.\n\t */\n\tresourceId?: string;\n\tprojectId?: string;\n\trepositoryId?: string;\n}\n\n/**\n * Why a provider request failed, when the failure itself says so:\n * - `unreachable`: a transport failure or server-side error prevented the provider from answering. The connection\n * still exists; this accompanies `kind: 'other'`, never an authentication warning.\n * - `oauth-app-not-allowed`: the organization does not let third-party OAuth apps in. On Azure DevOps this is the\n * organization policy \"Third-party application access via OAuth\", off by default for new organizations. An\n * organization admin enables it, or the user connects with a personal access token instead, which the policy\n * does not govern.\n * - `access-denied`: the account has no access to that organization or project (not a member, or lacking the\n * permission). Someone who administers it has to grant access.\n * - `conditional-access`: a Microsoft Entra Conditional Access policy blocked the request (Azure DevOps\n * `VS403463`). Its admin has to exempt the request, e.g. by location or device.\n *\n * None of these is healed by reconnecting, which is the point of naming them.\n */\nexport type ProviderWarningCauseReason =\n\t| 'oauth-app-not-allowed'\n\t| 'access-denied'\n\t| 'conditional-access'\n\t| 'unreachable';\n\n/** See {@link ProviderWarning.cause}. */\nexport interface ProviderWarningCause {\n\treason: ProviderWarningCauseReason;\n\t/** The provider's own error code, when it reports one (Azure DevOps `TF400813`, `VS403463`). */\n\tcode?: string;\n\t/** Where the setting behind the refusal is changed, when this layer can address it. */\n\tremedyUrl?: string;\n}\n\n/** Which repository / project / resource an omission is attributed to. All fields optional; a scope may name none. */\nexport interface ProviderWarningOmissionScope extends ProviderWarningScope {\n\tproviderId?: string;\n}\n\nexport interface ProviderWarningOmission {\n\tkind: ProviderWarningOmissionKind;\n\t/**\n\t * Whether anything would fetch the missing items, and what. Gate a \"load more\" affordance on this rather\n\t * than on `kind` — see {@link ProviderWarningOmissionRecovery}.\n\t */\n\trecovery: ProviderWarningOmissionRecovery;\n\t/**\n\t * The cap the provider enforces, when it reports one. NOT a result count for every kind: on\n\t * `recovery-budget` this is a REQUEST budget and must not be shown to a user as a number of results.\n\t */\n\tlimit?: number;\n\t/** Total matches the provider reported, when it reports one. Only GitHub's search cap does today. */\n\ttotalCount?: number;\n\t/**\n\t * The order the reachable window was selected under, as `field:direction`, when the omission is a result\n\t * ceiling.\n\t *\n\t * Present so a consumer can word its own \"N matched, showing the first M\" without assuming WHICH M: the\n\t * provider serves the top M under this key, so the sentence is only true if it names it. Absent for every\n\t * omission that isn't a ceiling, where no window was selected by an order.\n\t *\n\t * A union of both vocabularies rather than the issue one alone: `PullRequestSorting` happens to be a subset\n\t * today, so narrowing this to {@link IssueSorting} would still compile while describing only half the reads\n\t * that set it — and would break the day the PR search gains a key the issue search has no name for.\n\t */\n\tsort?: IssueSorting | PullRequestSorting;\n\t/** Which repository / project / resource was affected, when one is attributed. */\n\tscope?: ProviderWarningOmissionScope;\n}\n\nexport interface ProviderWarning {\n\tproviderId: IntegrationIds;\n\t/** Disambiguates connections on self-managed hosts (where one provider id spans multiple domains). */\n\tdomain?: string;\n\t/** The specific token/connection the read was pinned to, when a `connectionId` was supplied. */\n\tconnectionId?: string;\n\tmessage: string;\n\tkind: ProviderWarningKind;\n\t/** Convenience mirror of `kind === 'auth'`, scoped or not; read {@link scope} before prompting to reconnect. */\n\tisAuth: boolean;\n\t/**\n\t * Present when the failure was recorded against one sub-scope of the read (an organization, project or\n\t * repository) rather than against the connection. A scoped `auth` failure is that one scope refusing this\n\t * credential, e.g. an Azure DevOps organization that disallows third-party OAuth apps, one in another Entra\n\t * tenant, or a Conditional Access policy. Reconnecting cannot fix those, so this warning alone is no reason\n\t * to prompt for it.\n\t *\n\t * `kind` and `isAuth` are unaffected: a scoped 401 is still an authentication failure, and this field says\n\t * how far it reaches. It names at least one of its IDs, and is never set on an omission (which carries its\n\t * own {@link ProviderWarningOmission.scope}) or on a warning derived from a caught exception (see\n\t * {@link toProviderWarning}), even when that call targeted a single organization. The exception is a batch\n\t * read's refused target, which names its scope: the Azure DevOps organization and project, the repository on\n\t * other git hosts, or the tracker's resource.\n\t *\n\t * Its ABSENCE means account-wide or unattributed, so existing handling stays correct without it.\n\t *\n\t * A scoped `auth` failure also means the credential itself was accepted. A dead token can come back as nothing\n\t * but scoped refusals wherever a read reaches its scopes without an uncached request to the connection first:\n\t * discovery served from a per-token cache (Azure DevOps, Bitbucket, Jira Cloud) or an SDK fan-out across the\n\t * requested repositories (Bitbucket Data Center). So when a read's only auth failures are scoped, those providers\n\t * confirm the credential with one uncached check first, and a refused credential fails the whole read with an\n\t * unscoped `auth` warning. A batch read checks it only when every target was refused, since a target that\n\t * answered already proved it. A refusal the provider attributes to the credential itself, like Bitbucket's or Jira\n\t * Cloud's for a token missing the OAuth scopes a read needs, which a reconnect fixes, is published unscoped too,\n\t * once for the connection, while the scopes that answered keep their results.\n\t *\n\t * So the promise holds for a read that carries no unscoped `auth` warning of its own; one that does already asks\n\t * for a reconnect, and its other scoped refusals are not checked. Two exceptions stay scoped even then. A check\n\t * that could not complete or was denied (a network error, a throttle, a `403`, Bitbucket Data Center refusing a\n\t * credential it authenticated, or a Bitbucket Data Center project access token, whose user the check cannot\n\t * find) proves nothing, so the warnings are published unconfirmed, with no {@link cause}, and the next read\n\t * checks again. And a credential confirmed within the last minute is not probed again, so a revocation can take\n\t * up to a minute to surface.\n\t */\n\tscope?: ProviderWarningScope;\n\t/**\n\t * Why the provider request failed, when the failure itself says so: see {@link ProviderWarningCauseReason}. Switch on\n\t * `reason` to recommend a fix instead of a reconnect; `message` then carries the same explanation as prose.\n\t *\n\t * `unreachable` accompanies a transport or server failure with `kind: 'other'`. Credential refusal causes are\n\t * set only on a scoped `auth` warning whose credential was confirmed first (see {@link scope}), because the\n\t * refusals they name are indistinguishable from a dead credential until then: Azure DevOps answers a\n\t * third-party OAuth app its organization disallows exactly as it answers an expired token. Only Azure DevOps\n\t * reports one today. Its absence proves nothing about the cause.\n\t */\n\tcause?: ProviderWarningCause;\n\t/**\n\t * Present when this warning describes results the read could not return even though the request itself\n\t * SUCCEEDED — a provider-enforced cap, an exhausted recovery budget, a page budget, or a sub-scope the read\n\t * did not drain.\n\t *\n\t * Its presence is the signal: an omission is not a failure. Message it as incompleteness rather than as a\n\t * failed read, and do NOT derive that from `message`, which is English prose and subject to rewording.\n\t * `kind` stays `'other'` for these, so the failure discriminant keeps meaning exactly what it meant before\n\t * this field existed.\n\t *\n\t * Whether anything would fetch the rest is a SEPARATE question — read {@link ProviderWarningOmission.recovery},\n\t * not `kind`, and never assume a retry of the same request returns more.\n\t *\n\t * `limit` / `totalCount` / `scope` are forwarded only when they are reported; most omissions carry none of\n\t * the three, so render correctly without them — and see {@link ProviderWarningOmission.limit} before\n\t * showing that figure as a result count.\n\t *\n\t * Its ABSENCE proves nothing. It is never set on a warning derived from a caught exception (see\n\t * {@link toProviderWarning}) or from a structured scope failure — those are failures, and the field would\n\t * be a lie there. But it is also absent whenever incompleteness was reported without naming what was left\n\t * out, so treat a bare `kind: 'other'` warning as unclassified rather than as a proven failure.\n\t */\n\tomission?: ProviderWarningOmission;\n}\n\nexport interface ProviderPageInfo {\n\t/**\n\t * The 1-based POSITION of the returned page. One convention across every paged read, page-number and\n\t * cursor paging alike, so a `getNextPageParam`-style consumer can key off it uniformly:\n\t * - the page number the provider itself reported, when it reports one (authoritative);\n\t * - else the position the caller addressed: the page encoded in a threaded page cursor, or the `page`\n\t * supplied alongside an opaque cursor (1 when the caller supplied no `page`);\n\t * - else, for a read that can be advanced by page number, the requested `page` — the provider either\n\t * honored it or the internal drain reached it (see the paging contract on `IntegrationManager`);\n\t * - else 1: a cursor-only read with no cursor threaded back ignores a requested page number and answers\n\t * with its first page, so echoing the request would mislabel page 1 as page N.\n\t *\n\t * A page past the provider's terminal cursor still reports the requested `page` with empty `items` — an\n\t * empty page N, never page N-1 relabeled.\n\t *\n\t * Continue a cursor-paged read from `cursor`, NOT from `currentPage + 1`: a cursor-only host can't be\n\t * addressed by number, so this is a position label and not always a resumable request parameter.\n\t */\n\tcurrentPage: number;\n\t/**\n\t * The page size IN EFFECT, which is not always the one requested — it is whichever of these the read can\n\t * actually vouch for:\n\t * - the size the provider reported for the page it served (numbered-page hosts), else\n\t * - the `itemsPerPage` that was applied to the request (repo-scoped reads, which forward it), else\n\t * - `items.length`, for a read that takes no page size at all: the account-wide PR/issue reads, `listRepos`\n\t * (cursor-only), and `listIssueTrackerIssuesPage`, whose `itemsPerPage` counts PROJECTS rather than issues.\n\t *\n\t * So it is a description of the page, not an echo of the request: don't derive a total from\n\t * `currentPage * itemsPerPage`, and don't read `items.length < itemsPerPage` as \"last page\" — `hasMore` /\n\t * `cursor` are the only continuation signals.\n\t */\n\titemsPerPage: number;\n\t/**\n\t * A COMPLETENESS assertion, not a mode flag: `true` only when a sweep drained every page of every target\n\t * without truncating or failing (`!truncated && !fetchFailed`). Set exclusively by `sweepPullRequests` /\n\t * `sweepClosedPullRequests` and absent on every paged read, so `allPages !== true` does NOT by itself mean\n\t * \"this was a single page\".\n\t *\n\t * This is the signal to gate on before caching a sweep as authoritative: unlike `truncated` it is `false`\n\t * for BOTH kinds of incompleteness, so it can't be misread as a benign cap.\n\t */\n\tallPages?: boolean;\n\t/**\n\t * True when the read stopped before it could confirm it had everything. Deliberately does NOT distinguish\n\t * WHY, and a consumer must not assume it means a provider ceiling — a sweep sets it from three different\n\t * origins:\n\t * - a provider-side ceiling or per-scope backstop propagated from below (e.g. GitHub Search's 1000-result\n\t * cap): the missing items are NOT reachable, so this really is \"complete to the provider's limit\";\n\t * - the sweep's OWN `maxPages` cap (default 100) with a usable cursor still in hand: the missing items ARE\n\t * reachable and were simply not fetched — raise `maxPages` to get them;\n\t * - the provider reporting another page but handing back no usable cursor: not reachable.\n\t *\n\t * Only the second is recoverable, and a sweep exposes no continuation cursor, so treating a truncated sweep\n\t * as a complete set silently drops reachable data in that case. Prefer `allPages` for the cache decision.\n\t */\n\ttruncated?: boolean;\n}\n\nexport interface ProviderResult<T> {\n\titems: T[];\n\twarnings: ProviderWarning[];\n\t/**\n\t * True when `items` is incomplete — distinguishes a failed or truncated flat read from a genuinely empty\n\t * result. Paged results additionally use `page.truncated` when a completed page could not confirm it\n\t * drained everything.\n\t */\n\tfetchFailed?: boolean;\n}\n\nexport interface ProviderPagedResult<T> extends ProviderResult<T> {\n\tpage: ProviderPageInfo;\n\thasMore: boolean;\n\t/**\n\t * Opaque cursor for cursor-based paging (GraphQL, per-repo/per-project cursors, etc.). For hosts that\n\t * require the previous page's cursor, consumers should pass this value back to the next `cursor` option.\n\t * A retry-only cursor may remain when `hasMore` is false: `hasMore` means automatic forward progress,\n\t * while explicitly reusing such a cursor retries failed work without creating an infinite paging loop.\n\t */\n\tcursor?: string;\n}\n\nexport interface ProviderSweepResult<T> extends ProviderResult<T> {\n\tpage: ProviderPageInfo;\n\thasMore: boolean;\n\t/**\n\t * Providers whose top-level read failed before returning any usable page. Partial per-scope failures stay\n\t * represented by `warnings` + `fetchFailed` and are intentionally excluded.\n\t */\n\tfailedProviderIds: IntegrationIds[];\n\t/**\n\t * Providers whose read started successfully but could not produce an authoritative complete slice (for\n\t * example, a later page failed, collection metadata reported a partial scope, or a paging backstop was hit).\n\t * Kept separate from\n\t * `failedProviderIds` so consumers can accept healthy sibling providers while preserving an older snapshot\n\t * for a provider whose returned slice has a gap.\n\t */\n\tincompleteProviderIds: IntegrationIds[];\n}\n\nexport interface ProviderBroadenResult<T> extends ProviderPagedResult<T> {\n\tbroadenedProviderIds: IntegrationIds[];\n\t/** Providers for which no requested org produced a usable issue result. */\n\tfailedProviderIds: IntegrationIds[];\n\t/** Providers with both a usable org result and at least one failed or truncated org slice. */\n\tincompleteProviderIds: IntegrationIds[];\n\tfanOutCount: number;\n}\n\nexport type RepositoryResolutionStatus =\n\t| 'resolved'\n\t| 'not-found'\n\t| 'unauthorized'\n\t| 'unsupported-provider'\n\t| 'invalid-remote-url'\n\t| 'host-mismatch'\n\t| 'undetermined';\n\nexport interface RepositoryIdentity {\n\tproviderId: IntegrationIds;\n\tdomain: string;\n\t/** The provider's canonical owner/namespace (follows renames), falling back to the parsed remote when omitted. */\n\towner: string;\n\t/** The provider's canonical repo name (follows renames), falling back to the parsed remote when omitted. */\n\tname: string;\n\tproject?: string;\n\t/** The original input remote URL, so the caller can key the resolution back to the remote it asked about. */\n\tremoteUrl: string;\n\t/**\n\t * True when the provider's canonical owner/name differ from what the input remote URL carried — i.e. the\n\t * repo was renamed/moved host-side and the local remote is stale. Case-insensitive, mirroring gkcli's\n\t * `EqualFold` compare so hosts that echo the input casing (e.g. Bitbucket Server/Azure) aren't flagged.\n\t */\n\trenamed: boolean;\n}\n\nexport interface RepositoryResolution {\n\tstatus: RepositoryResolutionStatus;\n\tidentity?: RepositoryIdentity;\n\twarning?: ProviderWarning;\n}\n\nexport interface ResolveRepositoryResult {\n\tresolution: RepositoryResolution;\n}\n\nconst maxProviderWarningMessageLength = 500;\n\n/** A caught error's message as a warning can carry it: an HTML page becomes its status, and prose is capped. */\nexport function providerWarningMessage(ex: unknown): string {\n\tconst raw = (ex instanceof Error ? ex.message : String(ex)).trim();\n\tconst carrier = ex as { status?: unknown; response?: { status?: unknown } } | null | undefined;\n\tconst status =\n\t\ttypeof carrier?.status === 'number'\n\t\t\t? carrier.status\n\t\t\t: typeof carrier?.response?.status === 'number'\n\t\t\t\t? carrier.response.status\n\t\t\t\t: undefined;\n\n\t// Gateways commonly answer API requests with a complete HTML error page. That payload is neither actionable\n\t// nor suitable for a warning DTO consumed by UIs and logs; preserve the status without leaking the document.\n\tif (/<(?:!doctype\\s+html|html|head|body)\\b/i.test(raw)) {\n\t\treturn status != null ? `Provider request failed with status ${status}.` : 'Provider request failed.';\n\t}\n\n\tif (!raw) {\n\t\treturn status != null ? `Provider request failed with status ${status}.` : 'Provider request failed.';\n\t}\n\treturn raw.length > maxProviderWarningMessageLength\n\t\t? `${raw.slice(0, maxProviderWarningMessageLength - 3)}...`\n\t\t: raw;\n}\n\n/**\n * Normalized org/workspace/group shape returned by the provider facade.\n * `name` is the provider identifier to pass to follow-up reads, while `org` is an optional display label.\n */\nexport interface ProviderOrganization {\n\tid: string;\n\tproviderId: IntegrationIds;\n\tname: string;\n\torg?: string;\n\turl: string;\n}\n\n/** Normalized repository shape returned by the provider facade. */\nexport interface ProviderRepositoryShape {\n\tid: string;\n\tnamespace: string;\n\tname: string;\n\t/** Azure DevOps project; `undefined` for hosts without a project layer. */\n\tproject?: string;\n\t/** Web (browser) URL, when the provider exposes it. */\n\turl?: string;\n\t/** HTTPS clone URL, when available. */\n\tcloneUrlHttps?: string;\n\t/** SSH clone URL, when available. */\n\tcloneUrlSsh?: string;\n\t/** Default branch name, when the provider reports it. */\n\tdefaultBranch?: string;\n}\n\n/**\n * Classifies a caught provider exception into a neutral {@link ProviderWarning}. Ordering matters:\n * `instanceof` is checked most-specific-first so a rate-limit isn't mislabeled as a generic error and\n * a 404 isn't mislabeled as auth.\n */\nexport function toProviderWarning(\n\tproviderId: IntegrationIds,\n\tdomain: string | undefined,\n\tconnectionId: string | undefined,\n\tex: unknown,\n): ProviderWarning {\n\tlet kind: ProviderWarning['kind'];\n\tif (ex instanceof AuthenticationError) {\n\t\tkind = 'auth';\n\t} else if (ex instanceof RequestRateLimitError) {\n\t\tkind = 'rate-limit';\n\t} else if (ex instanceof RequestNotFoundError) {\n\t\tkind = 'not-found';\n\t} else if (isUnsupportedSortError(ex)) {\n\t\tkind = 'unsupported';\n\t} else {\n\t\tkind = 'other';\n\t}\n\n\treturn {\n\t\tproviderId: providerId,\n\t\tdomain: domain,\n\t\tconnectionId: connectionId,\n\t\tmessage: providerWarningMessage(ex),\n\t\tkind: kind,\n\t\tisAuth: kind === 'auth',\n\t\t...(kind === 'other' && isProviderUnreachableError(ex) ? { cause: { reason: 'unreachable' as const } } : {}),\n\t};\n}\n\n/**\n * A scope's identity, as the stable string that keys it.\n *\n * The single definition of what \"the same scope\" means, shared by the failure and omission dedup keys in\n * `providerPaging.ts` and by {@link providerWarningKey} below, so a scope gaining a field is one edit rather\n * than three. `providerId` is included: the same repository ID under two providers is two scopes.\n *\n * The parameter is structural rather than the SDK's `CollectionScope` so this module keeps naming no\n * `@gitkraken/provider-apis` types (see the export block in `index.ts`) while still serving its SDK-facing\n * callers, which pass that type in unchanged.\n */\nexport function collectionScopeKey(scope: ProviderWarningOmissionScope | undefined): string {\n\treturn [scope?.providerId ?? '', scope?.resourceId ?? '', scope?.projectId ?? '', scope?.repositoryId ?? ''].join(\n\t\t' ',\n\t);\n}\n\n/**\n * The omission's contribution to a warning's identity — empty when there is none, so a warning without an\n * omission keeps deduping exactly as it did before the field existed.\n *\n * Two omissions of different kinds do produce different `message` values today, so message alone would still\n * separate them. That is incidental: the premise of `omission` is that consumers must not depend on prose\n * carrying the distinguishing fact, and this key must not either.\n */\nfunction providerWarningOmissionKey(omission: ProviderWarningOmission | undefined): string {\n\tif (omission == null) return '';\n\n\treturn [\n\t\tomission.kind,\n\t\tomission.recovery,\n\t\tomission.limit ?? '',\n\t\tomission.totalCount ?? '',\n\t\tcollectionScopeKey(omission.scope),\n\t].join(' ');\n}\n\n/**\n * Strips the omission from every warning in `warnings` when the read as a whole failed.\n *\n * An omission asserts the request SUCCEEDED, and a drain only learns it failed AFTER it may have emitted one:\n * an early page can report its own truncation and then a later page can die. Deciding per warning, at the\n * moment each is built, cannot see that future — so the aggregate is reconciled once, here, where\n * `fetchFailed` is final. Call it at the point a read returns its `fetchFailed`.\n *\n * Re-dedupes as it goes: the omission is part of a warning's identity, so two warnings that differed only\n * there become identical once it is gone, and the array's contract is that no two entries are equal.\n *\n * Mutates in place: the warning array is the one being returned, and callers accumulate into it across pages.\n */\nexport function reconcileOmissionsWithFailure(warnings: ProviderWarning[], fetchFailed: boolean): void {\n\tif (!fetchFailed || !warnings.some(w => w.omission != null)) return;\n\n\tconst reconciled: ProviderWarning[] = [];\n\tfor (const warning of warnings) {\n\t\tif (warning.omission == null) {\n\t\t\tappendDedupedWarning(reconciled, warning);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst { omission: _omission, ...rest } = warning;\n\t\tappendDedupedWarning(reconciled, rest);\n\t}\n\n\twarnings.splice(0, warnings.length, ...reconciled);\n}\n\n/**\n * A stable key for deduplicating warnings accumulated across drained pages / fan-out scopes.\n *\n * The scope and the cause are keyed for the reason the omission is (see {@link providerWarningOmissionKey}): today's\n * failure messages happen to spell them out, but two failures that differ in either must stay two warnings even if\n * they don't.\n *\n * `message` stays LAST. It is the only free-form segment — provider prose, spaces and all — so anything\n * appended after it could be impersonated by a message that happens to end in the same text.\n */\nfunction providerWarningKey(warning: ProviderWarning): string {\n\treturn [\n\t\twarning.providerId,\n\t\twarning.connectionId ?? '',\n\t\twarning.domain ?? '',\n\t\twarning.kind,\n\t\tcollectionScopeKey(warning.scope),\n\t\twarning.cause?.reason ?? '',\n\t\tproviderWarningOmissionKey(warning.omission),\n\t\twarning.message,\n\t].join(' ');\n}\n\n/**\n * Appends `warning` to `into` only when an equal warning (by provider/connection/domain/kind/message, plus the\n * structured scope, cause and omission when present) is absent.\n */\nexport function appendDedupedWarning(into: ProviderWarning[], warning: ProviderWarning): void {\n\tconst key = providerWarningKey(warning);\n\tif (into.some(existing => providerWarningKey(existing) === key)) return;\n\n\tinto.push(warning);\n}\n"],"mappings":";;;;AAyWA,MAAM,kCAAkC;;AAGxC,SAAgB,uBAAuB,IAAqB;CAC3D,MAAM,OAAO,cAAc,QAAQ,GAAG,UAAU,OAAO,EAAE,EAAA,CAAG,KAAK;CACjE,MAAM,UAAU;CAChB,MAAM,SACL,OAAO,SAAS,WAAW,WACxB,QAAQ,SACR,OAAO,SAAS,UAAU,WAAW,WACpC,QAAQ,SAAS,SACjB,KAAA;CAIL,IAAI,yCAAyC,KAAK,GAAG,GACpD,OAAO,UAAU,OAAO,uCAAuC,OAAO,KAAK;CAG5E,IAAI,CAAC,KACJ,OAAO,UAAU,OAAO,uCAAuC,OAAO,KAAK;CAE5E,OAAO,IAAI,SAAS,kCACjB,GAAG,IAAI,MAAM,GAAG,GAAmC,EAAE,OACrD;AACJ;;;;;;AAoCA,SAAgB,kBACf,YACA,QACA,cACA,IACkB;CAClB,IAAI;CACJ,IAAI,cAAc,qBACjB,OAAO;MACD,IAAI,cAAc,uBACxB,OAAO;MACD,IAAI,cAAc,sBACxB,OAAO;MACD,IAAI,uBAAuB,EAAE,GACnC,OAAO;MAEP,OAAO;CAGR,OAAO;EACM;EACJ;EACM;EACd,SAAS,uBAAuB,EAAE;EAC5B;EACN,QAAQ,SAAS;EACjB,GAAI,SAAS,WAAW,2BAA2B,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,cAAuB,EAAE,IAAI,CAAC;CAC3G;AACD;;;;;;;;;;;;AAaA,SAAgB,mBAAmB,OAAyD;CAC3F,OAAO;EAAC,OAAO,cAAc;EAAI,OAAO,cAAc;EAAI,OAAO,aAAa;EAAI,OAAO,gBAAgB;CAAE,CAAC,CAAC,KAC5G,GACD;AACD;;;;;;;;;AAUA,SAAS,2BAA2B,UAAuD;CAC1F,IAAI,YAAY,MAAM,OAAO;CAE7B,OAAO;EACN,SAAS;EACT,SAAS;EACT,SAAS,SAAS;EAClB,SAAS,cAAc;EACvB,mBAAmB,SAAS,KAAK;CAClC,CAAC,CAAC,KAAK,GAAG;AACX;;;;;;;;;;;;;;AAeA,SAAgB,8BAA8B,UAA6B,aAA4B;CACtG,IAAI,CAAC,eAAe,CAAC,SAAS,MAAK,MAAK,EAAE,YAAY,IAAI,GAAG;CAE7D,MAAM,aAAgC,CAAC;CACvC,KAAK,MAAM,WAAW,UAAU;EAC/B,IAAI,QAAQ,YAAY,MAAM;GAC7B,qBAAqB,YAAY,OAAO;GACxC;EACD;EAEA,MAAM,EAAE,UAAU,WAAW,GAAG,SAAS;EACzC,qBAAqB,YAAY,IAAI;CACtC;CAEA,SAAS,OAAO,GAAG,SAAS,QAAQ,GAAG,UAAU;AAClD;;;;;;;;;;;AAYA,SAAS,mBAAmB,SAAkC;CAC7D,OAAO;EACN,QAAQ;EACR,QAAQ,gBAAgB;EACxB,QAAQ,UAAU;EAClB,QAAQ;EACR,mBAAmB,QAAQ,KAAK;EAChC,QAAQ,OAAO,UAAU;EACzB,2BAA2B,QAAQ,QAAQ;EAC3C,QAAQ;CACT,CAAC,CAAC,KAAK,GAAG;AACX;;;;;AAMA,SAAgB,qBAAqB,MAAyB,SAAgC;CAC7F,MAAM,MAAM,mBAAmB,OAAO;CACtC,IAAI,KAAK,MAAK,aAAY,mBAAmB,QAAQ,MAAM,GAAG,GAAG;CAEjE,KAAK,KAAK,OAAO;AAClB"}
|
|
@@ -3,9 +3,8 @@
|
|
|
3
3
|
export type CancellationReason = 'aborted' | 'timeout' | 'unknown';
|
|
4
4
|
/**
|
|
5
5
|
* A standalone CancellationError for use in the library.
|
|
6
|
-
* Uses a symbol brand so that
|
|
7
|
-
*
|
|
8
|
-
* recognized by `isCancellationError`.
|
|
6
|
+
* Uses a symbol brand so that instances from any bundle are recognized
|
|
7
|
+
* by `isCancellationError`.
|
|
9
8
|
*/
|
|
10
9
|
export declare class CancellationError extends Error {
|
|
11
10
|
readonly original?: Error | undefined;
|
|
@@ -3,9 +3,8 @@ import { getScopedCounter } from "./counter.js";
|
|
|
3
3
|
const cancellationErrorBrand = Symbol.for("CancellationError");
|
|
4
4
|
/**
|
|
5
5
|
* A standalone CancellationError for use in the library.
|
|
6
|
-
* Uses a symbol brand so that
|
|
7
|
-
*
|
|
8
|
-
* recognized by `isCancellationError`.
|
|
6
|
+
* Uses a symbol brand so that instances from any bundle are recognized
|
|
7
|
+
* by `isCancellationError`.
|
|
9
8
|
*/
|
|
10
9
|
var CancellationError = class extends Error {
|
|
11
10
|
original;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cancellation.js","names":[],"sources":["../../../utils/src/cancellation.ts"],"sourcesContent":["import { getScopedCounter } from './counter.js';\n\nconst cancellationErrorBrand = Symbol.for('CancellationError');\n\n/** Why an operation was cancelled: a caller abort, a timeout, or a termination whose cause is unknown. */\nexport type CancellationReason = 'aborted' | 'timeout' | 'unknown';\n\n/**\n * A standalone CancellationError for use in the library.\n * Uses a symbol brand so that both this class and the extension's\n * CancellationError (which extends vscode.CancellationError) are\n * recognized by `isCancellationError`.\n */\nexport class CancellationError extends Error {\n\t// TS-only nominal brand (not read anywhere) — without it, `CancellationError` has the same\n\t// structural shape as any other `Error` subtype, so `isCancellationError`'s negative narrowing\n\t// (`if (isCancellationError(ex)) throw ex;`) collapses an unrelated error union to `never` instead\n\t// of leaving it narrowed. The runtime brand stays a symbol (below) for the cross-realm check.\n\tprivate readonly _cancellationErrorBrand: true = true;\n\n\tconstructor(\n\t\tpublic readonly original?: Error,\n\t\tpublic readonly reason?: CancellationReason,\n\t) {\n\t\tsuper();\n\t\t// A symbol-keyed computed class field can't be typed for `isolatedDeclarations` (only well-known\n\t\t// symbols like `Symbol.iterator` qualify), so the brand is set here with the same runtime shape\n\t\t// (writable/enumerable/configurable) a plain field assignment would produce.\n\t\tObject.defineProperty(this, cancellationErrorBrand, {\n\t\t\tvalue: true,\n\t\t\twritable: true,\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t});\n\t\tthis.name = 'CancellationError';\n\n\t\tif (this.original) {\n\t\t\tif (this.original.message.startsWith('Operation cancelled')) {\n\t\t\t\tthis.message = this.original.message;\n\t\t\t} else {\n\t\t\t\tthis.message = `Operation cancelled; ${this.original.message}`;\n\t\t\t}\n\t\t} else {\n\t\t\tthis.message = 'Operation cancelled';\n\t\t}\n\t\tError.captureStackTrace?.(this, new.target);\n\t}\n}\n\nexport function isCancellationError(ex: unknown): ex is CancellationError {\n\treturn (\n\t\t(ex instanceof Error && (cancellationErrorBrand in ex || ex.name === 'CancellationError')) ||\n\t\t(ex instanceof DOMException && ex.name === 'AbortError')\n\t);\n}\n\n/**\n * Races a promise against an `AbortSignal`. If the signal fires before\n * the promise settles, the returned promise rejects with `CancellationError`.\n * If the promise settles first, the signal listener is cleaned up.\n */\nexport function raceWithSignal<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n\tif (signal.aborted) return Promise.reject(new CancellationError());\n\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst onAbort = () => reject(new CancellationError());\n\t\tsignal.addEventListener('abort', onAbort, { once: true });\n\t\tpromise.then(\n\t\t\tv => {\n\t\t\t\tsignal.removeEventListener('abort', onAbort);\n\t\t\t\tresolve(v);\n\t\t\t},\n\t\t\t(e: unknown) => {\n\t\t\t\tsignal.removeEventListener('abort', onAbort);\n\t\t\t\treject(e instanceof Error ? e : new Error(String(e)));\n\t\t\t},\n\t\t);\n\t});\n}\n\n/**\n * Races a promise against a timeout. If `ms` elapses before the promise settles, the returned promise\n * rejects with `CancellationError`. If the promise settles first, the timer is cleared. Parallels\n * `raceWithSignal`, with a timer standing in for the signal.\n *\n * When `abortOnTimeout` is provided, it is aborted on timeout — so a caller can link the underlying operation to\n * it (e.g. via `AbortSignal.any`) and have it torn down instead of orphaned. Abort is best-effort (a truly-stuck\n * op may ignore it); the returned promise rejects on timeout regardless of whether the underlying op settles.\n */\nexport function raceWithTimeout<T>(promise: Promise<T>, ms: number, abortOnTimeout?: AbortController): Promise<T> {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tconst error = new CancellationError(new Error(`Timed out after ${ms}ms`), 'timeout');\n\t\t\tabortOnTimeout?.abort(error);\n\t\t\treject(error);\n\t\t}, ms);\n\t\t// Don't let the timeout timer keep a (Node) process alive on its own — a still-pending promise shouldn't\n\t\t// hold the event loop open just for its backstop (no-op in the browser, where setTimeout returns a number).\n\t\tif (typeof timer !== 'number') {\n\t\t\ttimer.unref();\n\t\t}\n\t\tpromise.then(\n\t\t\tv => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve(v);\n\t\t\t},\n\t\t\t(e: unknown) => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\treject(e instanceof Error ? e : new Error(String(e)));\n\t\t\t},\n\t\t);\n\t});\n}\n\n/**\n * Aggregates multiple caller `AbortSignal`s into a single signal that\n * only fires when **all** callers have cancelled (the inverse of `AbortSignal.any()`).\n *\n * Designed for shared-promise caching: each caller registers their signal,\n * and the underlying operation receives the aggregate signal. Individual callers\n * can cancel early (via `raceWithSignal`), but the operation continues as long\n * as at least one caller is still active.\n */\nexport class AbortAggregate {\n\tprivate readonly controller = new AbortController();\n\tprivate activeCount = 0;\n\t/** One listener-remover per registration (NOT keyed by signal), so adding the same signal twice is safe. */\n\tprivate readonly cleanups = new Set<() => void>();\n\n\t/** The aggregate signal — only fires when all callers have cancelled. */\n\tget signal(): AbortSignal {\n\t\treturn this.controller.signal;\n\t}\n\n\t/**\n\t * Register a caller.\n\t * - If `cancellation` is provided, the caller is auto-removed when it fires.\n\t * - If `cancellation` is `undefined`, the caller is \"permanent\" — the aggregate\n\t * can never fire while it's active. Call the returned cleanup on promise settle.\n\t * - The same signal instance may safely be added more than once — each registration is tracked and cleaned up\n\t * independently, so no listener leaks.\n\t * @returns A cleanup function to unregister the caller.\n\t */\n\tadd(cancellation?: AbortSignal): () => void {\n\t\tthis.activeCount++;\n\n\t\tif (cancellation == null) {\n\t\t\treturn () => {\n\t\t\t\tthis.activeCount--;\n\t\t\t\tthis.checkAbort();\n\t\t\t};\n\t\t}\n\n\t\tif (cancellation.aborted) {\n\t\t\tthis.activeCount--;\n\t\t\tthis.checkAbort();\n\t\t\treturn () => {};\n\t\t}\n\n\t\t// Track this registration's listener removal individually (a Set of removers, NOT keyed by the signal) so\n\t\t// adding the same signal twice can't overwrite the other's cleanup. `settled` keeps both exit paths (abort\n\t\t// vs. manual cleanup) idempotent and preserves the accounting: only `onAbort` decrements `activeCount`.\n\t\tlet settled = false;\n\t\tlet remove: () => void;\n\t\tconst onAbort = () => {\n\t\t\tif (settled) return;\n\n\t\t\tsettled = true;\n\t\t\tthis.cleanups.delete(remove);\n\t\t\tthis.activeCount--;\n\t\t\tthis.checkAbort();\n\t\t};\n\t\tremove = () => cancellation.removeEventListener('abort', onAbort);\n\t\tcancellation.addEventListener('abort', onAbort, { once: true });\n\t\tthis.cleanups.add(remove);\n\n\t\treturn () => {\n\t\t\tif (settled) return;\n\n\t\t\tsettled = true;\n\t\t\tthis.cleanups.delete(remove);\n\t\t\tremove();\n\t\t};\n\t}\n\n\tprivate checkAbort(): void {\n\t\tif (this.activeCount <= 0 && !this.controller.signal.aborted) {\n\t\t\tthis.controller.abort();\n\t\t}\n\t}\n\n\t/** Remove all abort listeners. Call when the cached promise settles. */\n\tdispose(): void {\n\t\tfor (const remove of this.cleanups) {\n\t\t\tremove();\n\t\t}\n\t\tthis.cleanups.clear();\n\t}\n}\n\nconst signalIds = new WeakMap<AbortSignal, number>();\nconst signalIdCounter = getScopedCounter();\n\n/**\n * Returns a stable, unique numeric ID for the given AbortSignal.\n * Used to differentiate concurrent git commands that have different\n * cancellation signals, so one caller aborting doesn't cancel another.\n */\nexport function getAbortSignalId(signal: AbortSignal | undefined): string {\n\tif (signal == null) return '';\n\n\tlet id = signalIds.get(signal);\n\tif (id == null) {\n\t\tid = signalIdCounter.next();\n\t\tsignalIds.set(signal, id);\n\t}\n\treturn String(id);\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"cancellation.js","names":[],"sources":["../../../utils/src/cancellation.ts"],"sourcesContent":["import { getScopedCounter } from './counter.js';\n\nconst cancellationErrorBrand = Symbol.for('CancellationError');\n\n/** Why an operation was cancelled: a caller abort, a timeout, or a termination whose cause is unknown. */\nexport type CancellationReason = 'aborted' | 'timeout' | 'unknown';\n\n/**\n * A standalone CancellationError for use in the library.\n * Uses a symbol brand so that instances from any bundle are recognized\n * by `isCancellationError`.\n */\nexport class CancellationError extends Error {\n\t// TS-only nominal brand (not read anywhere) — without it, `CancellationError` has the same\n\t// structural shape as any other `Error` subtype, so `isCancellationError`'s negative narrowing\n\t// (`if (isCancellationError(ex)) throw ex;`) collapses an unrelated error union to `never` instead\n\t// of leaving it narrowed. The runtime brand stays a symbol (below) for the cross-realm check.\n\tprivate readonly _cancellationErrorBrand: true = true;\n\n\tconstructor(\n\t\tpublic readonly original?: Error,\n\t\tpublic readonly reason?: CancellationReason,\n\t) {\n\t\tsuper();\n\t\t// A symbol-keyed computed class field can't be typed for `isolatedDeclarations` (only well-known\n\t\t// symbols like `Symbol.iterator` qualify), so the brand is set here with the same runtime shape\n\t\t// (writable/enumerable/configurable) a plain field assignment would produce.\n\t\tObject.defineProperty(this, cancellationErrorBrand, {\n\t\t\tvalue: true,\n\t\t\twritable: true,\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t});\n\t\tthis.name = 'CancellationError';\n\n\t\tif (this.original) {\n\t\t\tif (this.original.message.startsWith('Operation cancelled')) {\n\t\t\t\tthis.message = this.original.message;\n\t\t\t} else {\n\t\t\t\tthis.message = `Operation cancelled; ${this.original.message}`;\n\t\t\t}\n\t\t} else {\n\t\t\tthis.message = 'Operation cancelled';\n\t\t}\n\t\tError.captureStackTrace?.(this, new.target);\n\t}\n}\n\nexport function isCancellationError(ex: unknown): ex is CancellationError {\n\treturn (\n\t\t(ex instanceof Error && (cancellationErrorBrand in ex || ex.name === 'CancellationError')) ||\n\t\t(ex instanceof DOMException && ex.name === 'AbortError')\n\t);\n}\n\n/**\n * Races a promise against an `AbortSignal`. If the signal fires before\n * the promise settles, the returned promise rejects with `CancellationError`.\n * If the promise settles first, the signal listener is cleaned up.\n */\nexport function raceWithSignal<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n\tif (signal.aborted) return Promise.reject(new CancellationError());\n\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst onAbort = () => reject(new CancellationError());\n\t\tsignal.addEventListener('abort', onAbort, { once: true });\n\t\tpromise.then(\n\t\t\tv => {\n\t\t\t\tsignal.removeEventListener('abort', onAbort);\n\t\t\t\tresolve(v);\n\t\t\t},\n\t\t\t(e: unknown) => {\n\t\t\t\tsignal.removeEventListener('abort', onAbort);\n\t\t\t\treject(e instanceof Error ? e : new Error(String(e)));\n\t\t\t},\n\t\t);\n\t});\n}\n\n/**\n * Races a promise against a timeout. If `ms` elapses before the promise settles, the returned promise\n * rejects with `CancellationError`. If the promise settles first, the timer is cleared. Parallels\n * `raceWithSignal`, with a timer standing in for the signal.\n *\n * When `abortOnTimeout` is provided, it is aborted on timeout — so a caller can link the underlying operation to\n * it (e.g. via `AbortSignal.any`) and have it torn down instead of orphaned. Abort is best-effort (a truly-stuck\n * op may ignore it); the returned promise rejects on timeout regardless of whether the underlying op settles.\n */\nexport function raceWithTimeout<T>(promise: Promise<T>, ms: number, abortOnTimeout?: AbortController): Promise<T> {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tconst error = new CancellationError(new Error(`Timed out after ${ms}ms`), 'timeout');\n\t\t\tabortOnTimeout?.abort(error);\n\t\t\treject(error);\n\t\t}, ms);\n\t\t// Don't let the timeout timer keep a (Node) process alive on its own — a still-pending promise shouldn't\n\t\t// hold the event loop open just for its backstop (no-op in the browser, where setTimeout returns a number).\n\t\tif (typeof timer !== 'number') {\n\t\t\ttimer.unref();\n\t\t}\n\t\tpromise.then(\n\t\t\tv => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve(v);\n\t\t\t},\n\t\t\t(e: unknown) => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\treject(e instanceof Error ? e : new Error(String(e)));\n\t\t\t},\n\t\t);\n\t});\n}\n\n/**\n * Aggregates multiple caller `AbortSignal`s into a single signal that\n * only fires when **all** callers have cancelled (the inverse of `AbortSignal.any()`).\n *\n * Designed for shared-promise caching: each caller registers their signal,\n * and the underlying operation receives the aggregate signal. Individual callers\n * can cancel early (via `raceWithSignal`), but the operation continues as long\n * as at least one caller is still active.\n */\nexport class AbortAggregate {\n\tprivate readonly controller = new AbortController();\n\tprivate activeCount = 0;\n\t/** One listener-remover per registration (NOT keyed by signal), so adding the same signal twice is safe. */\n\tprivate readonly cleanups = new Set<() => void>();\n\n\t/** The aggregate signal — only fires when all callers have cancelled. */\n\tget signal(): AbortSignal {\n\t\treturn this.controller.signal;\n\t}\n\n\t/**\n\t * Register a caller.\n\t * - If `cancellation` is provided, the caller is auto-removed when it fires.\n\t * - If `cancellation` is `undefined`, the caller is \"permanent\" — the aggregate\n\t * can never fire while it's active. Call the returned cleanup on promise settle.\n\t * - The same signal instance may safely be added more than once — each registration is tracked and cleaned up\n\t * independently, so no listener leaks.\n\t * @returns A cleanup function to unregister the caller.\n\t */\n\tadd(cancellation?: AbortSignal): () => void {\n\t\tthis.activeCount++;\n\n\t\tif (cancellation == null) {\n\t\t\treturn () => {\n\t\t\t\tthis.activeCount--;\n\t\t\t\tthis.checkAbort();\n\t\t\t};\n\t\t}\n\n\t\tif (cancellation.aborted) {\n\t\t\tthis.activeCount--;\n\t\t\tthis.checkAbort();\n\t\t\treturn () => {};\n\t\t}\n\n\t\t// Track this registration's listener removal individually (a Set of removers, NOT keyed by the signal) so\n\t\t// adding the same signal twice can't overwrite the other's cleanup. `settled` keeps both exit paths (abort\n\t\t// vs. manual cleanup) idempotent and preserves the accounting: only `onAbort` decrements `activeCount`.\n\t\tlet settled = false;\n\t\tlet remove: () => void;\n\t\tconst onAbort = () => {\n\t\t\tif (settled) return;\n\n\t\t\tsettled = true;\n\t\t\tthis.cleanups.delete(remove);\n\t\t\tthis.activeCount--;\n\t\t\tthis.checkAbort();\n\t\t};\n\t\tremove = () => cancellation.removeEventListener('abort', onAbort);\n\t\tcancellation.addEventListener('abort', onAbort, { once: true });\n\t\tthis.cleanups.add(remove);\n\n\t\treturn () => {\n\t\t\tif (settled) return;\n\n\t\t\tsettled = true;\n\t\t\tthis.cleanups.delete(remove);\n\t\t\tremove();\n\t\t};\n\t}\n\n\tprivate checkAbort(): void {\n\t\tif (this.activeCount <= 0 && !this.controller.signal.aborted) {\n\t\t\tthis.controller.abort();\n\t\t}\n\t}\n\n\t/** Remove all abort listeners. Call when the cached promise settles. */\n\tdispose(): void {\n\t\tfor (const remove of this.cleanups) {\n\t\t\tremove();\n\t\t}\n\t\tthis.cleanups.clear();\n\t}\n}\n\nconst signalIds = new WeakMap<AbortSignal, number>();\nconst signalIdCounter = getScopedCounter();\n\n/**\n * Returns a stable, unique numeric ID for the given AbortSignal.\n * Used to differentiate concurrent git commands that have different\n * cancellation signals, so one caller aborting doesn't cancel another.\n */\nexport function getAbortSignalId(signal: AbortSignal | undefined): string {\n\tif (signal == null) return '';\n\n\tlet id = signalIds.get(signal);\n\tif (id == null) {\n\t\tid = signalIdCounter.next();\n\t\tsignalIds.set(signal, id);\n\t}\n\treturn String(id);\n}\n"],"mappings":"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"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gitkraken/core-gitlens",
|
|
3
3
|
"description": "GitLens core — shared Git / AI / GitHub primitives for internal GitKraken consumption",
|
|
4
|
-
"version": "0.10.
|
|
4
|
+
"version": "0.10.4",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "GitKraken",
|
|
@@ -246,7 +246,7 @@
|
|
|
246
246
|
"@octokit/types": "17.0.0",
|
|
247
247
|
"@vscode/l10n": "0.0.18",
|
|
248
248
|
"fast-string-truncated-width": "3.0.3",
|
|
249
|
-
"ignore": "7.0.
|
|
249
|
+
"ignore": "7.0.9",
|
|
250
250
|
"vscode-uri": "3.2.0"
|
|
251
251
|
},
|
|
252
252
|
"devDependencies": {
|