@charles7c/git-forge 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1265 @@
1
+ /**
2
+ * Core data models and the adapter-facing type vocabulary.
3
+ *
4
+ * Two rules govern these models:
5
+ *
6
+ * 1. Field names keep GitHub's `snake_case` shape verbatim. No camelCase
7
+ * rewriting, so a caller's existing GitHub code keeps working.
8
+ * 2. Every model carries `provider` / `owner` / `repo` so a value can be traced
9
+ * back to the platform and repository it came from without extra context.
10
+ *
11
+ * Capability identifiers also live here (rather than in `adapters/types.ts`)
12
+ * because the error model references them and `core` must never import
13
+ * `adapters`. `adapters/types.ts` re-exports them for adapter authors.
14
+ */
15
+ /** Hosting platforms supported by v0.1.0. */
16
+ type Provider = 'github' | 'gitee' | 'atomgit';
17
+ /** Runtime list of {@link Provider}, in the order used by documentation. */
18
+ declare const PROVIDERS: readonly ["github", "gitee", "atomgit"];
19
+ /**
20
+ * Platform-native issue identifier.
21
+ *
22
+ * GitHub uses a number, AtomGit a numeric string (`"205"`), and Gitee a base32
23
+ * code (`"IEXA01"`) that cannot be parsed as a number at all. Accepting both
24
+ * lets a caller pass through whatever the platform reports.
25
+ */
26
+ type NativeId = string | number;
27
+ /** Normalized issue state. Platform-specific states are folded into these two. */
28
+ type IssueState = 'open' | 'closed';
29
+ /**
30
+ * Normalized pull-request state.
31
+ *
32
+ * AtomGit reports a third value, `merged`; adapters fold it into `closed` and
33
+ * set `merged: true` so the contract stays binary.
34
+ */
35
+ type PullRequestState = 'open' | 'closed';
36
+ /** Merge strategies offered by all three platforms. */
37
+ type MergeMethod = 'merge' | 'squash' | 'rebase';
38
+ /** How file content is encoded in a `createOrUpdateFile` / `pushFiles` call. */
39
+ type ContentEncoding = 'base64' | 'utf8';
40
+ /** Minimal repository reference used by every domain method. */
41
+ interface RepoRef {
42
+ owner: string;
43
+ repo: string;
44
+ }
45
+ /** Provenance fields present on every returned model. */
46
+ interface ModelIdentity {
47
+ provider: Provider;
48
+ owner: string;
49
+ repo: string;
50
+ }
51
+ /** A platform account as far as the unified models need it. */
52
+ interface UserRef {
53
+ login: string;
54
+ name?: string;
55
+ avatar_url?: string;
56
+ }
57
+ /** An issue, normalized across the three platforms. */
58
+ interface Issue extends ModelIdentity {
59
+ /** Platform-native issue number as text, including codes and leading zeroes. */
60
+ number: string;
61
+ /** Available only for decimal digit strings representable as a safe integer. */
62
+ number_as_number?: number;
63
+ title: string;
64
+ state: IssueState;
65
+ body?: string;
66
+ html_url: string;
67
+ labels: string[];
68
+ user?: UserRef;
69
+ assignees?: UserRef[];
70
+ comments_count?: number;
71
+ closed_at?: string;
72
+ /** ISO 8601 string, kept exactly as the platform sent it (offset preserved). */
73
+ created_at: string;
74
+ /** ISO 8601 string, kept exactly as the platform sent it (offset preserved). */
75
+ updated_at: string;
76
+ }
77
+ /** Source/target branch reference on a pull request. */
78
+ interface PullRequestRef {
79
+ ref: string;
80
+ sha: string;
81
+ }
82
+ /** A pull request, normalized across the three platforms. */
83
+ interface PullRequest extends ModelIdentity {
84
+ /** Pull-request numbers are integers on all three platforms. */
85
+ number: number;
86
+ title: string;
87
+ state: PullRequestState;
88
+ /**
89
+ * Whether the pull request was merged.
90
+ *
91
+ * GitHub reads `merged`, Gitee derives it from `merged_at`, AtomGit from
92
+ * `state === 'merged'`.
93
+ */
94
+ merged: boolean;
95
+ merged_at?: string;
96
+ html_url: string;
97
+ /** Absent if the provider does not return the source branch reference. */
98
+ head?: PullRequestRef;
99
+ base: PullRequestRef;
100
+ body?: string;
101
+ draft?: boolean;
102
+ mergeable?: boolean;
103
+ user?: UserRef;
104
+ additions?: number;
105
+ deletions?: number;
106
+ changed_files?: number;
107
+ created_at: string;
108
+ updated_at: string;
109
+ }
110
+ /** A repository, normalized across the three platforms. */
111
+ interface Repository extends ModelIdentity {
112
+ /** Repository name; identical to {@link Repository.repo}. */
113
+ name: string;
114
+ /**
115
+ * Human-facing repository URL.
116
+ *
117
+ * Gitee's raw value is a clone URL ending in `.git` and is stripped; AtomGit
118
+ * leaves `html_url` null and exposes `web_url` instead, which is used as-is.
119
+ */
120
+ html_url: string;
121
+ private: boolean;
122
+ default_branch: string;
123
+ full_name?: string;
124
+ description?: string;
125
+ fork?: boolean;
126
+ language?: string;
127
+ created_at?: string;
128
+ updated_at?: string;
129
+ }
130
+ /** A single file's content as returned by the contents API. */
131
+ interface FileContent extends ModelIdentity {
132
+ path: string;
133
+ /** Payload encoded per {@link FileContent.encoding}. */
134
+ content: string;
135
+ /**
136
+ * Encoding of {@link FileContent.content}. All three platforms currently
137
+ * report `base64`; the field stays a plain string so an unusual value is
138
+ * reported rather than rejected.
139
+ */
140
+ encoding: string;
141
+ sha?: string;
142
+ size?: number;
143
+ html_url?: string;
144
+ type?: string;
145
+ }
146
+ /** Result of a write that produced a commit. */
147
+ interface FileWriteResult extends ModelIdentity {
148
+ /** sha of the commit that contains the change. Always present. */
149
+ commit_sha: string;
150
+ /** Web URL of that commit; all three platforms expose one. */
151
+ commit_html_url: string;
152
+ /** Every path touched by this write, in the order given by the caller. */
153
+ paths: string[];
154
+ /** Web URL per path where obtainable; `undefined` where the platform omits it. */
155
+ file_html_urls?: (string | undefined)[];
156
+ branch: string;
157
+ }
158
+ /** A branch, normalized across the three platforms. */
159
+ interface Branch extends ModelIdentity {
160
+ name: string;
161
+ commit_sha: string;
162
+ protected?: boolean;
163
+ /**
164
+ * Derived by the adapter as `<webBase>/<owner>/<repo>/tree/<name>`.
165
+ *
166
+ * No platform returns this field (nor a `_links` object), so it is omitted
167
+ * when no web base URL is configured rather than fabricated.
168
+ */
169
+ html_url?: string;
170
+ }
171
+ /** Commit authorship metadata. */
172
+ interface CommitAuthor {
173
+ name: string;
174
+ email: string;
175
+ /** ISO 8601 string, kept as the platform sent it. */
176
+ date: string;
177
+ }
178
+ /** A commit, normalized across the three platforms. */
179
+ interface Commit extends ModelIdentity {
180
+ sha: string;
181
+ message: string;
182
+ html_url: string;
183
+ author?: CommitAuthor;
184
+ committer?: CommitAuthor;
185
+ /** Parent commit shas, root-commit order preserved. */
186
+ parents?: string[];
187
+ }
188
+ /** An issue or pull-request comment. */
189
+ interface Comment extends ModelIdentity {
190
+ /** Comment identifier, normalized to a number. */
191
+ id: number;
192
+ body: string;
193
+ /**
194
+ * Optional: Gitee and AtomGit comment objects do not carry `html_url`.
195
+ * Adapters fall back to the parent issue/PR URL and never invent anchors.
196
+ */
197
+ html_url?: string;
198
+ created_at: string;
199
+ updated_at?: string;
200
+ user?: UserRef;
201
+ }
202
+ /** Runtime list of every method-level capability, grouped by domain. */
203
+ declare const CAPABILITY_IDS: readonly ["issues.list", "issues.get", "issues.create", "issues.update", "issues.listComments", "issues.createComment", "pulls.list", "pulls.get", "pulls.create", "pulls.merge", "pulls.listComments", "pulls.createComment", "repos.list", "repos.get", "repos.create", "repos.getFileContents", "files.create", "files.update", "files.delete", "files.pushFiles", "branches.list", "branches.create", "commits.list", "commits.get"];
204
+ /**
205
+ * The 24 method-level capabilities delivered by v0.1.0.
206
+ *
207
+ * Derived from {@link CAPABILITY_IDS}, so the type and the runtime list cannot
208
+ * drift apart.
209
+ */
210
+ type CapabilityId = (typeof CAPABILITY_IDS)[number];
211
+ /** Runtime list of every parameter-level capability. */
212
+ declare const PARAM_CAPABILITY_IDS: readonly ["pulls.list.headFilter", "pulls.list.milestoneFilter", "issues.list.milestoneFilter", "files.pushFiles.atomic"];
213
+ /**
214
+ * Parameter-level capabilities.
215
+ *
216
+ * A method can exist while one of its filters is not supported — AtomGit has
217
+ * pull-request listing but no `head` filter. Declaring those separately lets the
218
+ * facade fail loudly instead of silently returning an unfiltered result.
219
+ */
220
+ type ParamCapabilityId = (typeof PARAM_CAPABILITY_IDS)[number];
221
+ /** Whether a provider implements a capability. */
222
+ type CapabilityState = 'supported' | 'unsupported';
223
+ /** Per-provider support matrix for method-level capabilities. */
224
+ type CapabilityTable = Readonly<Record<CapabilityId, CapabilityState>>;
225
+ /** Per-provider support matrix for parameter-level capabilities. */
226
+ type ParamCapabilityTable = Readonly<Record<ParamCapabilityId, CapabilityState>>;
227
+ /** Options shared by every list method. */
228
+ interface ListOptions {
229
+ /**
230
+ * Maximum pages to fetch. Defaults to 10 and is capped at 100 so a huge
231
+ * repository cannot turn one call into unbounded traffic.
232
+ */
233
+ maxPages?: number;
234
+ }
235
+ /** Parameters of `listIssues`. */
236
+ interface ListIssuesParams extends RepoRef, ListOptions {
237
+ /** Reject with `PAGINATION_LIMIT` if the page budget may truncate the list. Defaults to false. */
238
+ requireComplete?: boolean;
239
+ state?: IssueState | 'all';
240
+ /** Comma-joined for both Gitee and AtomGit on the wire. */
241
+ labels?: string[];
242
+ /** Milestone number; Gitee's list filter only accepts a title, so it rejects this. */
243
+ milestone?: number;
244
+ }
245
+ /** Parameters of `getIssue`. */
246
+ interface GetIssueParams extends RepoRef {
247
+ number: NativeId;
248
+ }
249
+ /** Parameters of `createIssue`. */
250
+ interface CreateIssueParams extends RepoRef {
251
+ title: string;
252
+ body?: string;
253
+ labels?: string[];
254
+ milestone?: number;
255
+ }
256
+ /** Parameters of `updateIssue`. Omitted fields are left untouched. */
257
+ interface UpdateIssueParams extends RepoRef {
258
+ number: NativeId;
259
+ title?: string;
260
+ body?: string;
261
+ state?: IssueState;
262
+ labels?: string[];
263
+ milestone?: number;
264
+ }
265
+ /** Parameters of `listIssueComments` and `listPullRequestComments`. */
266
+ interface ListCommentsParams extends RepoRef, ListOptions {
267
+ number: NativeId;
268
+ }
269
+ /** Parameters of `createIssueComment` and `createPullRequestComment`. */
270
+ interface CreateCommentParams extends RepoRef {
271
+ number: NativeId;
272
+ body: string;
273
+ }
274
+ /** Parameters of `listPullRequests`. */
275
+ interface ListPullRequestsParams extends RepoRef, ListOptions {
276
+ state?: PullRequestState | 'all';
277
+ /**
278
+ * Source-branch filter. Supported by GitHub and Gitee; AtomGit has no such
279
+ * filter and rejects the call rather than ignoring it.
280
+ */
281
+ head?: string;
282
+ base?: string;
283
+ labels?: string[];
284
+ milestone?: number;
285
+ }
286
+ /** Parameters of `getPullRequest`. */
287
+ interface GetPullRequestParams extends RepoRef {
288
+ number: number;
289
+ }
290
+ /** Parameters of `createPullRequest`. */
291
+ interface CreatePullRequestParams extends RepoRef {
292
+ title: string;
293
+ head: string;
294
+ base: string;
295
+ body?: string;
296
+ draft?: boolean;
297
+ }
298
+ /** Parameters of `mergePullRequest`. */
299
+ interface MergePullRequestParams extends RepoRef {
300
+ number: number;
301
+ merge_method?: MergeMethod;
302
+ commit_title?: string;
303
+ commit_message?: string;
304
+ }
305
+ /**
306
+ * Parameters of `listRepositories`.
307
+ *
308
+ * `org` and `user` are mutually exclusive; omitting both lists the
309
+ * authenticated user's repositories.
310
+ */
311
+ interface ListRepositoriesParams extends ListOptions {
312
+ org?: string;
313
+ user?: string;
314
+ }
315
+ /** Parameters of `getRepository`. */
316
+ type GetRepositoryParams = RepoRef;
317
+ /** Parameters of `createRepository`. */
318
+ interface CreateRepositoryParams {
319
+ name: string;
320
+ description?: string;
321
+ private?: boolean;
322
+ /** Create inside this organization instead of the authenticated user's account. */
323
+ org?: string;
324
+ auto_init?: boolean;
325
+ }
326
+ /** Parameters of `getFileContents`. */
327
+ interface GetFileContentsParams extends RepoRef {
328
+ path: string;
329
+ /** Branch name, tag or commit sha. */
330
+ ref?: string;
331
+ }
332
+ /** Parameters of `createOrUpdateFile`. */
333
+ interface CreateOrUpdateFileParams extends RepoRef {
334
+ path: string;
335
+ content: string;
336
+ message: string;
337
+ branch?: string;
338
+ /** Existing blob sha; required by all three platforms when updating. */
339
+ sha?: string;
340
+ /** Encoding of `content`. Defaults to `utf8`; use `base64` for pre-encoded bytes. */
341
+ encoding?: ContentEncoding;
342
+ }
343
+ /** Parameters of `deleteFile`. */
344
+ interface DeleteFileParams extends RepoRef {
345
+ path: string;
346
+ message: string;
347
+ /** Blob sha of the file being deleted. */
348
+ sha: string;
349
+ branch?: string;
350
+ }
351
+ /**
352
+ * Action of one entry in a `pushFiles` batch: a closed three-value set.
353
+ *
354
+ * There is deliberately no `upsert`. Gitee distinguishes `create` from `update`
355
+ * and answers 400 for the wrong one, while GitHub treats both as "write this
356
+ * content", so an explicit action is the only formulation correct on both
357
+ * without a per-file existence probe.
358
+ */
359
+ type PushFileAction = 'create' | 'update' | 'delete';
360
+ /** One file in a `pushFiles` batch. */
361
+ interface PushFileEntry {
362
+ /** Repository-relative path, without a leading slash. */
363
+ path: string;
364
+ /** Which of the three mutations this entry performs. */
365
+ action: PushFileAction;
366
+ /** Required for `create`/`update`; must be absent for `delete`. */
367
+ content?: string;
368
+ /** Encoding of {@link PushFileEntry.content}; defaults to `utf8`. */
369
+ encoding?: ContentEncoding;
370
+ }
371
+ /** Parameters of `pushFiles`. */
372
+ interface PushFilesParams extends RepoRef {
373
+ branch: string;
374
+ message: string;
375
+ files: PushFileEntry[];
376
+ }
377
+ /** Parameters of `listBranches`. */
378
+ type ListBranchesParams = RepoRef & ListOptions;
379
+ /** Parameters of `createBranch`. */
380
+ interface CreateBranchParams extends RepoRef {
381
+ /** New branch name. */
382
+ name: string;
383
+ /** Source branch name or commit sha. */
384
+ from: string;
385
+ }
386
+ /** Parameters of `listCommits`. */
387
+ interface ListCommitsParams extends RepoRef, ListOptions {
388
+ /** Branch name, tag or commit sha to start from. */
389
+ branch?: string;
390
+ }
391
+ /** Parameters of `getCommit`. */
392
+ interface GetCommitParams extends RepoRef {
393
+ sha: string;
394
+ }
395
+
396
+ /** The public error categories. */
397
+ type ErrorCode =
398
+ /** The provider does not implement the capability at all. */
399
+ 'UNSUPPORTED_ON_PROVIDER'
400
+ /** No token is configured for this provider; nothing was sent. */
401
+ | 'AUTH_MISSING'
402
+ /** The token was rejected, or a 403 that is not rate limiting. */
403
+ | 'AUTH_INVALID'
404
+ /** The resource does not exist or is not visible to this token. */
405
+ | 'NOT_FOUND'
406
+ /** A quota was exhausted, including 403 with zero remaining. */
407
+ | 'RATE_LIMITED'
408
+ /** Any upstream failure that maps to no narrower category. */
409
+ | 'PROVIDER_ERROR'
410
+ /** The call was rejected locally, or the upstream rejected its content. */
411
+ | 'INVALID_ARGUMENT'
412
+ /** Transport failed: DNS, TLS, connection reset, timeout. */
413
+ | 'NETWORK_ERROR'
414
+ /** A write call was blocked because the client is in read-only mode. */
415
+ | 'READONLY_BLOCKED'
416
+ /** The caller required a complete list, but the page budget was exhausted. */
417
+ | 'PAGINATION_LIMIT';
418
+ /** Runtime list of every error code, in documentation order. */
419
+ declare const ERROR_CODES: readonly ["UNSUPPORTED_ON_PROVIDER", "AUTH_MISSING", "AUTH_INVALID", "NOT_FOUND", "RATE_LIMITED", "PROVIDER_ERROR", "INVALID_ARGUMENT", "NETWORK_ERROR", "READONLY_BLOCKED", "PAGINATION_LIMIT"];
420
+ /** Serialized form produced by {@link GitForgeError.toJSON}. */
421
+ interface GitForgeErrorJson {
422
+ code: ErrorCode;
423
+ message: string;
424
+ provider?: Provider;
425
+ status?: number;
426
+ requestId?: string;
427
+ capability?: CapabilityId | ParamCapabilityId;
428
+ retryable: boolean;
429
+ }
430
+ /** Constructor input for {@link GitForgeError}. */
431
+ interface GitForgeErrorInit {
432
+ code: ErrorCode;
433
+ message: string;
434
+ provider?: Provider;
435
+ status?: number;
436
+ requestId?: string;
437
+ capability?: CapabilityId | ParamCapabilityId;
438
+ /** Defaults to {@link DEFAULT_RETRYABLE} for the code. */
439
+ retryable?: boolean;
440
+ cause?: unknown;
441
+ /** Known token values to strip from the message. */
442
+ secrets?: readonly string[];
443
+ }
444
+ /**
445
+ * Returns the default retryability of a code.
446
+ *
447
+ * Used by callers that must decide whether to retry before an error exists,
448
+ * and by {@link GitForgeError} when `retryable` is not supplied.
449
+ */
450
+ declare function defaultRetryable(code: ErrorCode): boolean;
451
+ /**
452
+ * A normalized failure from any layer of the library.
453
+ *
454
+ * Never construct a plain `Error` for an expected failure: callers branch on
455
+ * `code`, and `toJSON()` is the only sanctioned serialization path (notably for
456
+ * `bulk()` partial results and MCP tool errors).
457
+ */
458
+ declare class GitForgeError extends Error {
459
+ readonly code: ErrorCode;
460
+ readonly provider?: Provider;
461
+ readonly status?: number;
462
+ readonly requestId?: string;
463
+ readonly capability?: CapabilityId | ParamCapabilityId;
464
+ readonly retryable: boolean;
465
+ readonly cause?: unknown;
466
+ constructor(init: GitForgeErrorInit);
467
+ /**
468
+ * Serializes the error without headers, token values or the cause chain.
469
+ *
470
+ * Optional fields are omitted rather than set to `undefined`, so a JSON
471
+ * round-trip cannot reintroduce a key that was never known.
472
+ */
473
+ toJSON(): GitForgeErrorJson;
474
+ }
475
+ /** Returns `true` when a value is a {@link GitForgeError}. */
476
+ declare function isGitForgeError(value: unknown): value is GitForgeError;
477
+ /**
478
+ * Extracts a request id from response headers, then from the AtomGit error body.
479
+ *
480
+ * The body fallback is limited to exactly one key (`trace_id`): the whole body
481
+ * is never retained on the error object, which keeps upstream payloads (and any
482
+ * credentials they might contain) out of the public error surface.
483
+ *
484
+ * @returns The id, or `undefined` when no source has one. Never `''` and never
485
+ * a placeholder such as `'unknown'`, so callers can test truthiness.
486
+ */
487
+ declare function extractRequestId(headers: Headers | Readonly<Record<string, string | undefined>> | undefined, body?: unknown): string | undefined;
488
+ /**
489
+ * Pulls a short, safe diagnostic out of an upstream error body.
490
+ *
491
+ * Only the message-like fields of the three platforms are considered, and the
492
+ * result is truncated. This is the *only* body content allowed into an error
493
+ * message; the rest of the payload stays out.
494
+ */
495
+ declare function extractUpstreamMessage(body: unknown, maxLength?: number, secrets?: readonly string[]): string | undefined;
496
+ /**
497
+ * Whether an upstream 403 means "quota exhausted" rather than "forbidden".
498
+ *
499
+ * GitHub reports rate limiting this way instead of with 429; Gitee and AtomGit
500
+ * use 429. Detecting it keeps a retryable condition from being reported as a
501
+ * permanent authorization failure.
502
+ */
503
+ declare function isRateLimitResponse(status: number, headers: Headers | Readonly<Record<string, string | undefined>> | undefined): boolean;
504
+ /**
505
+ * Maps an HTTP response to a {@link GitForgeError}.
506
+ *
507
+ * @param provider Platform that produced the response.
508
+ * @param status HTTP status code.
509
+ * @param headers Response headers, for rate-limit and request-id detection.
510
+ * @param body Parsed response body, if any.
511
+ * @param context Short description of the attempt, e.g.
512
+ * `GET /repos/{owner}/{repo}/issues`. Templates only — never a
513
+ * concrete URL, which could carry a token.
514
+ * @param secrets Known token values to scrub from the message.
515
+ */
516
+ declare function errorFromResponse(params: {
517
+ provider: Provider;
518
+ status: number;
519
+ headers?: Headers | Readonly<Record<string, string | undefined>>;
520
+ body?: unknown;
521
+ context: string;
522
+ secrets?: readonly string[];
523
+ }): GitForgeError;
524
+ /**
525
+ * Maps an HTTP status to an error code.
526
+ *
527
+ * Ordering matters: 403 is checked for rate limiting before being treated as an
528
+ * authorization failure, because GitHub signals quota exhaustion with 403.
529
+ */
530
+ declare function mapStatusToCode(status: number, headers?: Headers | Readonly<Record<string, string | undefined>>): ErrorCode;
531
+ /**
532
+ * Retryability for a response-derived error.
533
+ *
534
+ * 5xx is retryable; any other `PROVIDER_ERROR` (405/409/…) is a permanent
535
+ * upstream complaint and must not be retried.
536
+ */
537
+ declare function retryableForStatus(code: ErrorCode, status: number): boolean;
538
+ /**
539
+ * Wraps a transport failure (fetch rejection, abort, timeout).
540
+ *
541
+ * Only safe context is retained, including response metadata if headers arrived.
542
+ */
543
+ declare function errorFromNetwork(params: {
544
+ provider: Provider;
545
+ context: string;
546
+ cause: unknown;
547
+ secrets?: readonly string[];
548
+ timeoutMs?: number;
549
+ response?: Response;
550
+ retryable?: boolean;
551
+ }): GitForgeError;
552
+ /** Builds the `UNSUPPORTED_ON_PROVIDER` error for a method-level capability. */
553
+ declare function unsupportedCapabilityError(provider: Provider, capability: CapabilityId | ParamCapabilityId): GitForgeError;
554
+ /** Builds the `AUTH_MISSING` error for a provider without a token. */
555
+ declare function authMissingError(provider: Provider, envVar: string): GitForgeError;
556
+ /** Builds the `READONLY_BLOCKED` error for a write capability. */
557
+ declare function readonlyBlockedError(provider: Provider, capability: CapabilityId, method: string): GitForgeError;
558
+ /** Builds the `INVALID_ARGUMENT` error for local parameter validation. */
559
+ declare function invalidArgumentError(message: string, provider?: Provider, capability?: CapabilityId | ParamCapabilityId): GitForgeError;
560
+
561
+ /** Outcome of one item in a bulk run. */
562
+ type BulkItemResult<T> = {
563
+ ok: true;
564
+ value: T;
565
+ index: number;
566
+ } | {
567
+ ok: false;
568
+ error: GitForgeErrorJson;
569
+ index: number;
570
+ };
571
+ /** Options for {@link bulk}. */
572
+ interface BulkOptions {
573
+ /**
574
+ * Maximum items in flight at once. Defaults to 4.
575
+ *
576
+ * Four keeps a batch inside typical 60-requests-per-hour quotas without
577
+ * triggering rate limiting itself.
578
+ */
579
+ concurrency?: number;
580
+ }
581
+ /** Default in-flight limit. */
582
+ declare const DEFAULT_BULK_CONCURRENCY = 4;
583
+ /**
584
+ * Runs a task over every item, isolating failures.
585
+ *
586
+ * The returned array always matches the input length and order, and this
587
+ * function never rejects: a failure becomes an `{ ok: false }` entry carrying
588
+ * `code`/`provider`/`status`/`requestId`, so a caller can tell a missing token
589
+ * from a 404 without re-parsing a message string.
590
+ *
591
+ * Non-`GitForgeError` failures are still isolated, but reported as
592
+ * `PROVIDER_ERROR` because a public API must not surface an untyped error.
593
+ *
594
+ * @throws GitForgeError `INVALID_ARGUMENT` only for caller mistakes — a
595
+ * non-array `items` or a concurrency below 1.
596
+ */
597
+ declare function bulk<A, T>(items: readonly A[], run: (item: A, index: number) => Promise<T>, options?: BulkOptions): Promise<BulkItemResult<T>[]>;
598
+ /** Partitions a result set into its successes and failures. */
599
+ declare function partitionBulk<T>(results: readonly BulkItemResult<T>[]): {
600
+ succeeded: T[];
601
+ failed: GitForgeErrorJson[];
602
+ };
603
+ /** Whether every item in a bulk run succeeded. */
604
+ declare function allSucceeded<T>(results: readonly BulkItemResult<T>[]): boolean;
605
+
606
+ /** Retry tuning knobs. */
607
+ interface RetryPolicy {
608
+ /** Retries after the initial attempt. Defaults to 3. */
609
+ maxRetries: number;
610
+ /** First backoff ceiling in milliseconds. Defaults to 500. */
611
+ baseMs: number;
612
+ /** Multiplier per attempt. Defaults to 2. */
613
+ factor: number;
614
+ /** Backoff ceiling in milliseconds. Defaults to 8 000. */
615
+ maxDelayMs: number;
616
+ /** Whether non-idempotent methods may be retried. Defaults to `false`. */
617
+ writes: boolean;
618
+ /** Maximum server-requested wait we will accept before giving up. Defaults to 60 s. */
619
+ maxRetryAfterMs: number;
620
+ }
621
+ /** Default policy. Read calls retry; write calls do not. */
622
+ declare const DEFAULT_RETRY_POLICY: RetryPolicy;
623
+ /**
624
+ * Whether a method is safe to retry without changing semantics.
625
+ *
626
+ * Deliberately conservative: `PUT` and `DELETE` are idempotent per RFC 9110 but
627
+ * are still treated as writes, because retrying a partially applied change can
628
+ * produce a second commit.
629
+ */
630
+ declare function isIdempotentMethod(method: string): boolean;
631
+ /** Merges caller overrides over the defaults. */
632
+ declare function resolveRetryPolicy(overrides?: Partial<RetryPolicy>): RetryPolicy;
633
+ /**
634
+ * Computes the backoff delay for an attempt.
635
+ *
636
+ * @param attempt 1-based retry number (1 is the first retry, not the initial
637
+ * request).
638
+ * @param policy Resolved policy.
639
+ * @param random Injected randomness; defaults to `Math.random`.
640
+ * @param retryAfterMs Server hint, already converted to milliseconds.
641
+ */
642
+ declare function computeDelay(attempt: number, policy: RetryPolicy, random: () => number, retryAfterMs?: number): number;
643
+ /**
644
+ * Parses a `retry-after` header into milliseconds.
645
+ *
646
+ * Handles both forms RFC 9110 allows: delta-seconds and an HTTP-date. Returns
647
+ * `undefined` for a missing or unparseable value so the caller falls back to its
648
+ * own backoff.
649
+ *
650
+ * @param maxMs Optional ceiling for callers that need a capped duration. The
651
+ * request layer omits it to distinguish an over-budget hint.
652
+ */
653
+ declare function parseRetryAfter(value: string | null | undefined, maxMs?: number): number | undefined;
654
+ /** What the request layer knows when deciding whether to try again. */
655
+ interface RetryDecisionInput {
656
+ /** 1-based number of the attempt that just failed. */
657
+ attempt: number;
658
+ method: string;
659
+ code: ErrorCode;
660
+ /** Upstream status, when a response was received. */
661
+ status?: number;
662
+ /** Uncapped minimum wait requested by the provider. */
663
+ retryAfterMs?: number;
664
+ policy: RetryPolicy;
665
+ }
666
+ /**
667
+ * Decides whether another attempt is warranted.
668
+ *
669
+ * Two independent conditions must hold: the error kind is retryable, and the
670
+ * method is one the policy allows to repeat. A write call therefore stays
671
+ * un-retried even on a 503 unless `retry.writes` was explicitly enabled.
672
+ */
673
+ declare function shouldRetry(input: RetryDecisionInput): boolean;
674
+ /**
675
+ * Reads the `retry-after` hint from response headers.
676
+ *
677
+ * Also understands `x-ratelimit-reset` (epoch seconds), which GitHub sends on a
678
+ * 403 quota exhaustion where `retry-after` may be absent.
679
+ */
680
+ declare function retryAfterFromHeaders(headers: Headers | Readonly<Record<string, string | undefined>> | undefined, maxMs?: number): number | undefined;
681
+ /**
682
+ * Whether a response should be retried, from the response alone.
683
+ *
684
+ * Exposed so the request layer can short-circuit before building an error
685
+ * object for a status it is about to retry anyway.
686
+ */
687
+ declare function isRetryableStatus(status: number, headers: Headers | Readonly<Record<string, string | undefined>> | undefined): boolean;
688
+
689
+ /**
690
+ * HTTP request layer: the single exit point for every network call.
691
+ *
692
+ * Adapters never call `fetch` directly. Concentrating transport here is what
693
+ * makes auth injection, timeouts, retries and redaction impossible to bypass,
694
+ * and it gives tests one seam to substitute.
695
+ */
696
+
697
+ /** How a provider authenticates a request. */
698
+ type AuthStyle = 'bearer' | 'query';
699
+ /** Authentication descriptor supplied by an adapter. */
700
+ interface AuthConfig {
701
+ /**
702
+ * `bearer` sets `Authorization: Bearer <token>`; `query` appends
703
+ * `access_token=<token>`.
704
+ *
705
+ * v0.1.0 defaults to `bearer` on all three platforms. `query` exists only for
706
+ * compatibility with older Gitee/AtomGit integrations and forces redaction of
707
+ * every URL that leaves this layer.
708
+ */
709
+ style: AuthStyle;
710
+ /** Query parameter name used when `style === 'query'`. Defaults to `access_token`. */
711
+ param?: string;
712
+ }
713
+ /**
714
+ * Where the body payload goes on the wire.
715
+ *
716
+ * - `json` — JSON request body (default when a body is present).
717
+ * - `form` — `application/x-www-form-urlencoded`.
718
+ * - `query` — body fields are moved into the query string. Gitee's
719
+ * `DELETE /repos/{o}/{r}/contents/{path}` takes `sha`/`message` this way.
720
+ */
721
+ type ParamsIn = 'query' | 'json' | 'form';
722
+ /** HTTP methods this layer issues. */
723
+ type HttpMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';
724
+ /** A single request description produced by an adapter. */
725
+ interface HttpRequestSpec {
726
+ method: HttpMethod;
727
+ /**
728
+ * Path template appended to the provider base URL, e.g.
729
+ * `/repos/{owner}/{repo}/issues`.
730
+ *
731
+ * Kept as a template so it can appear in error messages verbatim — a concrete
732
+ * URL might carry a token.
733
+ */
734
+ path: string;
735
+ /** Values substituted into `{placeholder}` segments of `path`. */
736
+ pathParams?: Readonly<Record<string, string>>;
737
+ /** Query parameters; `undefined` values are dropped. */
738
+ query?: Readonly<Record<string, string | number | boolean | undefined>>;
739
+ /** Payload for `POST`/`PATCH`/`PUT`/`DELETE`. */
740
+ body?: unknown;
741
+ /** How `body` is encoded. Defaults to `json` when a body is present. */
742
+ paramsIn?: ParamsIn;
743
+ /** Extra headers merged over the provider defaults. */
744
+ headers?: Readonly<Record<string, string>>;
745
+ }
746
+ /** A response, already parsed. */
747
+ interface HttpResponse<T = unknown> {
748
+ status: number;
749
+ headers: Headers;
750
+ json: T;
751
+ }
752
+ /** Options accepted by {@link HttpClient}. */
753
+ interface HttpClientOptions {
754
+ /** Platform base URL, without a trailing slash. */
755
+ baseUrl: string;
756
+ /** Platform this client speaks to; used for error context. */
757
+ provider: Provider;
758
+ /** Authentication descriptor; omit for unauthenticated calls. */
759
+ auth?: AuthConfig;
760
+ /** Token value. Never placed in a URL unless `auth.style === 'query'`. */
761
+ token?: string;
762
+ /** Headers sent with every request from this client. */
763
+ defaultHeaders?: Readonly<Record<string, string>>;
764
+ /** Injected transport. Defaults to `globalThis.fetch`. */
765
+ fetch?: typeof fetch;
766
+ /** Injected delay, so tests never wait. */
767
+ sleep?: (ms: number) => Promise<void>;
768
+ /** Injected randomness for jitter, so tests are deterministic. */
769
+ random?: () => number;
770
+ /** Per-request timeout in milliseconds. Defaults to 30 000. */
771
+ timeoutMs?: number;
772
+ /** Retry policy overrides. */
773
+ retry?: Partial<RetryPolicy>;
774
+ /** `User-Agent` sent with every request. */
775
+ userAgent?: string;
776
+ }
777
+ /** Default per-request timeout. */
778
+ declare const DEFAULT_TIMEOUT_MS = 30000;
779
+ /** Default `User-Agent` sent when the caller supplies none. */
780
+ declare const DEFAULT_USER_AGENT = "git-forge/0.1.0";
781
+ /**
782
+ * The request layer.
783
+ *
784
+ * One instance per provider per client: the token, provider and base URL are
785
+ * fixed at construction, so an adapter cannot accidentally send one platform's
786
+ * token to another.
787
+ */
788
+ declare class HttpClient {
789
+ #private;
790
+ get baseUrl(): string;
791
+ readonly timeoutMs: number;
792
+ readonly provider: Provider;
793
+ private readonly auth;
794
+ private readonly token;
795
+ private readonly defaultHeaders;
796
+ private readonly fetchImpl;
797
+ private readonly sleep;
798
+ private readonly random;
799
+ private readonly policy;
800
+ private readonly userAgent;
801
+ constructor(options: HttpClientOptions);
802
+ /** Whether a token was configured on this client. */
803
+ get hasToken(): boolean;
804
+ /**
805
+ * Renders a request for diagnostics.
806
+ *
807
+ * Query parameters are shown, path parameters are *not* substituted: the
808
+ * template is what belongs in a message, both because a concrete path can
809
+ * carry identifying data and because a caller needs the template to find the
810
+ * endpoint in the platform docs. Under query-style auth the parameter is
811
+ * present but redacted.
812
+ */
813
+ describe(spec: HttpRequestSpec): string;
814
+ /**
815
+ * Performs one logical request, retrying per policy.
816
+ *
817
+ * @throws GitForgeError always — a raw `Error` never escapes this method.
818
+ */
819
+ request<T = unknown>(spec: HttpRequestSpec): Promise<HttpResponse<T>>;
820
+ /** Performs exactly one attempt and reports its outcome without retrying. */
821
+ private attempt;
822
+ /** Honor delay headers even if reading the response body failed. */
823
+ private serverDelay;
824
+ /**
825
+ * Builds the concrete URL, including the token when query-style auth is on.
826
+ *
827
+ * `describe()` redacts the result, so the token exists only inside this
828
+ * function's return value and never reaches a message on its own.
829
+ */
830
+ private buildUrl;
831
+ /** Assembles request headers, injecting auth when bearer-style. */
832
+ private buildHeaders;
833
+ /** Encodes the body per `paramsIn`. */
834
+ private buildBody;
835
+ /** Builds a non-replayable error when success cannot be confirmed; uses header metadata only. */
836
+ invalidResponse(response: Pick<HttpResponse, 'status' | 'headers'>, message: string): GitForgeError;
837
+ /** Known token values, for scrubbing error messages. */
838
+ private secretValues;
839
+ }
840
+
841
+ /**
842
+ * Per-call context handed to an adapter method.
843
+ *
844
+ * One context is built per client and shared, so an adapter must not stash
845
+ * mutable state on it: concurrent calls would corrupt each other.
846
+ */
847
+ interface AdapterCtx {
848
+ /** Shared request layer — the only object allowed to perform HTTP. */
849
+ http: HttpClient;
850
+ /** This provider's method-level capability table. */
851
+ caps: CapabilityTable;
852
+ /** This provider's parameter-level capability table. */
853
+ paramCaps: ParamCapabilityTable;
854
+ /** Web base URL used to derive `Branch.html_url` without an extra request. */
855
+ webBaseUrl: string;
856
+ }
857
+ /** Parameters carrying the resolved provider, threaded through by the facade. */
858
+ type WithProvider<T> = T & {
859
+ provider: Provider;
860
+ };
861
+
862
+ /**
863
+ * `pushFiles` parameters, re-exported for adapter signatures.
864
+ *
865
+ * The shape is core's `PushFilesParams`, whose `files` entries already carry the
866
+ * closed `action` set; there is no separate adapter-only widening any more.
867
+ */
868
+ type PushFilesInput = PushFilesParams;
869
+ /** Issue domain: list / get / create / update and their comments. */
870
+ interface IssueDomain {
871
+ listIssues(ctx: AdapterCtx, params: WithProvider<ListIssuesParams>): Promise<Issue[]>;
872
+ getIssue(ctx: AdapterCtx, params: WithProvider<GetIssueParams>): Promise<Issue>;
873
+ createIssue(ctx: AdapterCtx, params: WithProvider<CreateIssueParams>): Promise<Issue>;
874
+ updateIssue(ctx: AdapterCtx, params: WithProvider<UpdateIssueParams>): Promise<Issue>;
875
+ listIssueComments(ctx: AdapterCtx, params: WithProvider<ListCommentsParams>): Promise<Comment[]>;
876
+ createIssueComment(ctx: AdapterCtx, params: WithProvider<CreateCommentParams>): Promise<Comment>;
877
+ }
878
+ /** Pull-request domain: list / get / create / merge and their comments. */
879
+ interface PullRequestDomain {
880
+ listPullRequests(ctx: AdapterCtx, params: WithProvider<ListPullRequestsParams>): Promise<PullRequest[]>;
881
+ getPullRequest(ctx: AdapterCtx, params: WithProvider<GetPullRequestParams>): Promise<PullRequest>;
882
+ createPullRequest(ctx: AdapterCtx, params: WithProvider<CreatePullRequestParams>): Promise<PullRequest>;
883
+ mergePullRequest(ctx: AdapterCtx, params: WithProvider<MergePullRequestParams>): Promise<PullRequest>;
884
+ listPullRequestComments(ctx: AdapterCtx, params: WithProvider<ListCommentsParams>): Promise<Comment[]>;
885
+ createPullRequestComment(ctx: AdapterCtx, params: WithProvider<CreateCommentParams>): Promise<Comment>;
886
+ }
887
+ /** Repository domain: list / get / create / read file contents. */
888
+ interface RepositoryDomain {
889
+ listRepositories(ctx: AdapterCtx, params: WithProvider<ListRepositoriesParams>): Promise<Repository[]>;
890
+ getRepository(ctx: AdapterCtx, params: WithProvider<GetRepositoryParams>): Promise<Repository>;
891
+ createRepository(ctx: AdapterCtx, params: WithProvider<CreateRepositoryParams>): Promise<Repository>;
892
+ getFileContents(ctx: AdapterCtx, params: WithProvider<GetFileContentsParams>): Promise<FileContent>;
893
+ }
894
+ /** Files domain: single-file create/update/delete plus batch push. */
895
+ interface FilesDomain {
896
+ createFile(ctx: AdapterCtx, params: WithProvider<CreateOrUpdateFileParams>): Promise<FileWriteResult>;
897
+ updateFile(ctx: AdapterCtx, params: WithProvider<CreateOrUpdateFileParams>): Promise<FileWriteResult>;
898
+ deleteFile(ctx: AdapterCtx, params: WithProvider<DeleteFileParams>): Promise<FileWriteResult>;
899
+ /**
900
+ * Commits every file in a single commit.
901
+ *
902
+ * A provider with no such endpoint must throw `UNSUPPORTED_ON_PROVIDER`
903
+ * instead of splitting the batch: the contract promises one commit, and a
904
+ * partial multi-commit write cannot be rolled back.
905
+ */
906
+ pushFiles(ctx: AdapterCtx, params: WithProvider<PushFilesInput>): Promise<FileWriteResult>;
907
+ }
908
+ /** Branch and commit domain. */
909
+ interface BranchCommitDomain {
910
+ listBranches(ctx: AdapterCtx, params: WithProvider<ListBranchesParams>): Promise<Branch[]>;
911
+ createBranch(ctx: AdapterCtx, params: WithProvider<CreateBranchParams>): Promise<Branch>;
912
+ listCommits(ctx: AdapterCtx, params: WithProvider<ListCommitsParams>): Promise<Commit[]>;
913
+ getCommit(ctx: AdapterCtx, params: WithProvider<GetCommitParams>): Promise<Commit>;
914
+ }
915
+ /** Everything a provider must implement. */
916
+ interface ProviderAdapter extends IssueDomain, PullRequestDomain, RepositoryDomain, FilesDomain, BranchCommitDomain {
917
+ readonly provider: Provider;
918
+ readonly capabilities: CapabilityTable;
919
+ readonly paramCapabilities: ParamCapabilityTable;
920
+ }
921
+
922
+ /** Parameters of a facade method: the call shape plus the target provider. */
923
+ type ProviderParams<T> = T & {
924
+ provider: Provider;
925
+ };
926
+ /**
927
+ * Credentials and endpoint overrides for one provider.
928
+ *
929
+ * `token` is optional: a client may be built before credentials exist, and the
930
+ * missing token surfaces as `AUTH_MISSING` at call time rather than at
931
+ * construction. That keeps a partially configured MCP server usable for the
932
+ * providers it does have.
933
+ */
934
+ interface ProviderCredentials {
935
+ /** Platform token, sent as `Authorization: Bearer`. Never logged. */
936
+ token?: string;
937
+ /** API base URL override, e.g. a GitHub Enterprise host. Must be `https:`. */
938
+ baseUrl?: string;
939
+ /** Web base URL used to derive `Branch.html_url`. Must be `https:`. */
940
+ webBaseUrl?: string;
941
+ }
942
+ /** Options accepted by {@link GitClient}. */
943
+ interface GitClientOptions {
944
+ github?: ProviderCredentials;
945
+ gitee?: ProviderCredentials;
946
+ atomgit?: ProviderCredentials;
947
+ /**
948
+ * Refuse every write capability with `READONLY_BLOCKED`.
949
+ *
950
+ * The check happens before dispatch, so a blocked write issues no request at
951
+ * all — the guarantee the MCP server relies on.
952
+ */
953
+ readonly?: boolean;
954
+ /** Injected transport. Defaults to `globalThis.fetch`. */
955
+ fetch?: typeof fetch;
956
+ /** Injected delay, so tests never wait on backoff. */
957
+ sleep?: (ms: number) => Promise<void>;
958
+ /** Injected randomness for jitter. */
959
+ random?: () => number;
960
+ /** Per-request timeout in milliseconds. Defaults to 30 000. */
961
+ timeoutMs?: number;
962
+ /** Retry policy overrides applied to every provider. */
963
+ retry?: Partial<RetryPolicy>;
964
+ /** `User-Agent` sent with every request. */
965
+ userAgent?: string;
966
+ }
967
+ /**
968
+ * The shared SDK client.
969
+ *
970
+ * One instance holds one {@link HttpClient} per provider, so a GitHub token can
971
+ * never reach a Gitee request even if an adapter were to pass the wrong context.
972
+ * Instances are safe to share: no method mutates client state.
973
+ */
974
+ declare class GitClient {
975
+ /** Whether write capabilities are refused. */
976
+ readonly readonly: boolean;
977
+ private readonly providers;
978
+ constructor(options?: GitClientOptions);
979
+ /** Providers that have a token configured. Names only — never values. */
980
+ configuredProviders(): Provider[];
981
+ /** Capability table of one provider, for callers that render a matrix. */
982
+ capabilities(provider: Provider): ProviderAdapter['capabilities'];
983
+ /** Parameter-level capability table of one provider. */
984
+ paramCapabilities(provider: Provider): ProviderAdapter['paramCapabilities'];
985
+ /** Lists issues, aggregating every page. */
986
+ listIssues(params: ProviderParams<ListIssuesParams>): Promise<Issue[]>;
987
+ /** Reads one issue. */
988
+ getIssue(params: ProviderParams<GetIssueParams>): Promise<Issue>;
989
+ /** Creates an issue. */
990
+ createIssue(params: ProviderParams<CreateIssueParams>): Promise<Issue>;
991
+ /** Updates an issue, leaving omitted fields untouched. */
992
+ updateIssue(params: ProviderParams<UpdateIssueParams>): Promise<Issue>;
993
+ /** Lists an issue's comments. */
994
+ listIssueComments(params: ProviderParams<ListCommentsParams>): Promise<Comment[]>;
995
+ /** Adds a comment to an issue. */
996
+ createIssueComment(params: ProviderParams<CreateCommentParams>): Promise<Comment>;
997
+ /**
998
+ * Lists pull requests.
999
+ *
1000
+ * The `head` filter goes through the parameter capability gate: AtomGit has no
1001
+ * such filter, and returning an unfiltered list would be undetectable.
1002
+ */
1003
+ listPullRequests(params: ProviderParams<ListPullRequestsParams>): Promise<PullRequest[]>;
1004
+ /** Reads one pull request. */
1005
+ getPullRequest(params: ProviderParams<GetPullRequestParams>): Promise<PullRequest>;
1006
+ /** Opens a pull request. */
1007
+ createPullRequest(params: ProviderParams<CreatePullRequestParams>): Promise<PullRequest>;
1008
+ /** Merges a pull request and returns its post-merge state. */
1009
+ mergePullRequest(params: ProviderParams<MergePullRequestParams>): Promise<PullRequest>;
1010
+ /** Lists a pull request's comments. */
1011
+ listPullRequestComments(params: ProviderParams<ListCommentsParams>): Promise<Comment[]>;
1012
+ /** Adds a comment to a pull request. */
1013
+ createPullRequestComment(params: ProviderParams<CreateCommentParams>): Promise<Comment>;
1014
+ /** Lists repositories of an org, a user, or the authenticated account. */
1015
+ listRepositories(params: ProviderParams<ListRepositoriesParams>): Promise<Repository[]>;
1016
+ /** Reads one repository. */
1017
+ getRepository(params: ProviderParams<GetRepositoryParams>): Promise<Repository>;
1018
+ /** Creates a repository. */
1019
+ createRepository(params: ProviderParams<CreateRepositoryParams>): Promise<Repository>;
1020
+ /** Reads one file's content. Directory paths are rejected by the adapters. */
1021
+ getFileContents(params: ProviderParams<GetFileContentsParams>): Promise<FileContent>;
1022
+ /**
1023
+ * Creates or replaces one file.
1024
+ *
1025
+ * `sha` selects the endpoint: absent means create, present means update. The
1026
+ * capability gate follows that choice so a provider that served one but not
1027
+ * the other would still be blocked correctly.
1028
+ */
1029
+ createOrUpdateFile(params: ProviderParams<CreateOrUpdateFileParams>): Promise<FileWriteResult>;
1030
+ /** Deletes one file. */
1031
+ deleteFile(params: ProviderParams<DeleteFileParams>): Promise<FileWriteResult>;
1032
+ /**
1033
+ * Commits every entry of a batch in one commit.
1034
+ *
1035
+ * AtomGit cannot do this and is refused by the capability gate; the batch is
1036
+ * never split into N single-file commits.
1037
+ */
1038
+ pushFiles(params: ProviderParams<PushFilesParams>): Promise<FileWriteResult>;
1039
+ /** Lists branches. */
1040
+ listBranches(params: ProviderParams<ListBranchesParams>): Promise<Branch[]>;
1041
+ /** Creates a branch from a branch name or commit sha. */
1042
+ createBranch(params: ProviderParams<CreateBranchParams>): Promise<Branch>;
1043
+ /** Lists commits. */
1044
+ listCommits(params: ProviderParams<ListCommitsParams>): Promise<Commit[]>;
1045
+ /** Reads one commit. */
1046
+ getCommit(params: ProviderParams<GetCommitParams>): Promise<Commit>;
1047
+ /**
1048
+ * Runs a task per item with partial-failure isolation.
1049
+ *
1050
+ * Delegates to `core/bulk.ts` so the batching semantics (bounded concurrency,
1051
+ * `{ok, index}` results, never rejecting) are identical to the standalone
1052
+ * helper.
1053
+ */
1054
+ bulk<A, T>(items: readonly A[], run: (item: A, index: number) => Promise<T>, options?: BulkOptions): Promise<BulkItemResult<T>[]>;
1055
+ /** Builds the per-provider bundle consumed by every method. */
1056
+ private resolve;
1057
+ /** Throws unless a parameter-level capability is supported. */
1058
+ private assertParamCapability;
1059
+ /**
1060
+ * Runs the five gates in order, then dispatches to the adapter.
1061
+ *
1062
+ * `async` on purpose: a gate failure must reject the returned promise rather
1063
+ * than throw synchronously, so `await`/`.catch()` behave identically for a
1064
+ * refused call and for a failed request.
1065
+ *
1066
+ * @param method Method name, used in validation and read-only messages.
1067
+ * @param capabilityFor Method-level capability, or a selector evaluated after validation.
1068
+ * @param params Caller payload; `provider` is read from it.
1069
+ * @param validate Parameter validator, run before any other gate.
1070
+ * @param run Adapter call, reached only when every gate passes.
1071
+ * @param paramGate Optional parameter-level capability check.
1072
+ */
1073
+ private dispatch;
1074
+ }
1075
+
1076
+ /**
1077
+ * Secret redaction.
1078
+ *
1079
+ * Three defenses share this module:
1080
+ *
1081
+ * 1. Tokens never reach a log line or an error message in the first place.
1082
+ * 2. {@link redactUrl} is the only supported way to turn a token-bearing URL
1083
+ * into something displayable.
1084
+ * 3. {@link scrubSecrets} is the last line of defense, applied to every
1085
+ * `GitForgeError` message as it is constructed.
1086
+ *
1087
+ * v0.1.0 authenticates with `Authorization: Bearer`, so tokens normally stay out
1088
+ * of URLs entirely. The query-style path is still supported for compatibility,
1089
+ * which is why this module cannot be dropped.
1090
+ */
1091
+ /** Placeholder substituted for every redacted value. */
1092
+ declare const REDACTED = "***";
1093
+ /**
1094
+ * Replaces every sensitive query-parameter value in a URL with `***`.
1095
+ *
1096
+ * Non-URL strings pass through with the same substitution applied, so this is
1097
+ * safe to call on anything.
1098
+ *
1099
+ * @example
1100
+ * redactUrl('https://gitee.com/api/v5/repos?access_token=abc123&page=1');
1101
+ * // 'https://gitee.com/api/v5/repos?access_token=***&page=1'
1102
+ */
1103
+ declare function redactUrl(url: string): string;
1104
+ /**
1105
+ * Removes known token values and any `key=value` secret pattern from free text.
1106
+ *
1107
+ * @param text Text to sanitize; non-strings are returned unchanged.
1108
+ * @param secrets Literal token values to strip. Only non-empty strings are
1109
+ * used, so an unset token cannot blank out the text.
1110
+ */
1111
+ declare function scrubSecrets(text: string, secrets?: readonly string[]): string;
1112
+ /** Returns `true` when a query key is treated as secret. */
1113
+ declare function isSensitiveKey(key: string): boolean;
1114
+
1115
+ /** Default page size. Hard-capped at the platforms' documented maximum. */
1116
+ declare const DEFAULT_PER_PAGE = 100;
1117
+ /** Upper bound accepted for `per_page`; platforms may silently truncate above it. */
1118
+ declare const MAX_PER_PAGE = 100;
1119
+ /** Default page limit for a single list call. */
1120
+ declare const DEFAULT_MAX_PAGES = 10;
1121
+ /** Hard cap on `maxPages`, so one call cannot page indefinitely. */
1122
+ declare const MAX_PAGES_LIMIT = 100;
1123
+ /**
1124
+ * Parses a `Link` header into a `rel -> url` map.
1125
+ *
1126
+ * @param header Raw header value, or `null` when absent.
1127
+ * @returns An empty object for a missing or empty header. Never throws: a
1128
+ * malformed header degrades to "no pagination hints", which the other
1129
+ * two signals cover.
1130
+ */
1131
+ declare function parseLinkHeader(header: string | null | undefined): Record<string, string>;
1132
+ /** Inputs for a single next-page decision. */
1133
+ interface PageSignals {
1134
+ /** Raw `Link` header, or `null` when the provider sent none. */
1135
+ link: string | null;
1136
+ /** `total_page` header as a number, or `null` when absent/unparseable. */
1137
+ totalPage: number | null;
1138
+ /** Page number just fetched, 1-based. */
1139
+ page: number;
1140
+ /** Number of items the just-fetched page contained. */
1141
+ itemCount: number;
1142
+ /** Page size that was requested. */
1143
+ perPage: number;
1144
+ }
1145
+ /**
1146
+ * Decides whether a following page exists.
1147
+ *
1148
+ * Providers may cap `per_page` below the requested size, so explicit hints
1149
+ * take precedence over page size. Strict collection prefers any reliable
1150
+ * continuation hint over terminal hints, even if the headers disagree.
1151
+ */
1152
+ declare function resolveNextPage(signals: PageSignals, strict?: boolean): boolean;
1153
+ /**
1154
+ * Reads `total_page` from response headers.
1155
+ *
1156
+ * @returns The page count, or `null` when the header is missing or not a
1157
+ * positive integer.
1158
+ */
1159
+ declare function readTotalPage(headers: Headers | Readonly<Record<string, string | undefined>> | undefined): number | null;
1160
+ /** Reads `total_count` from response headers, when a provider sends it. */
1161
+ declare function readTotalCount(headers: Headers | Readonly<Record<string, string | undefined>> | undefined): number | null;
1162
+ /**
1163
+ * Removes duplicates by identity key, keeping the first occurrence.
1164
+ *
1165
+ * Order is preserved and nothing is re-sorted: duplicated entries across pages
1166
+ * come from unstable platform ordering or items created mid-pagination, and
1167
+ * reordering would make the result non-reproducible.
1168
+ */
1169
+ declare function dedupeBy<T>(items: readonly T[], keyOf: (item: T) => string): T[];
1170
+ /** Clamps a requested page size into the supported range. */
1171
+ declare function normalizePerPage(value: number | undefined): number;
1172
+ /** Clamps a requested page limit into the supported range. */
1173
+ declare function normalizeMaxPages(value: number | undefined): number;
1174
+ /** A page as returned by one request, plus what pagination needs to continue. */
1175
+ interface PageResult<T> {
1176
+ items: T[];
1177
+ headers: Headers;
1178
+ status: number;
1179
+ /** Parsed body, untyped; callers narrow it to `T[]`. */
1180
+ raw: T[];
1181
+ }
1182
+ /** Options for {@link collectPages}. */
1183
+ interface CollectOptions<T> extends ListOptions {
1184
+ /** Page size; clamped to `[1, 100]`. */
1185
+ perPage?: number;
1186
+ /** Reject instead of returning partial items when another page is indicated at the cap. */
1187
+ requireComplete?: boolean;
1188
+ /** Extracts the array of items from a page body. */
1189
+ selectItems: (raw: unknown, ctx: {
1190
+ page: number;
1191
+ response: HttpResponse;
1192
+ }) => T[];
1193
+ /** Identity used for cross-page deduplication. */
1194
+ keyOf: (item: T) => string;
1195
+ /** Query parameters merged into every page request. */
1196
+ query?: Readonly<Record<string, string | number | boolean | undefined>>;
1197
+ }
1198
+ /**
1199
+ * Fetches every page of a list endpoint and returns the merged, deduplicated
1200
+ * result in page order.
1201
+ *
1202
+ * Stops when pagination signals indicate the end or the budget is exhausted.
1203
+ * By default the budget can truncate results; `requireComplete` rejects when
1204
+ * the final allowed page still indicates more data.
1205
+ */
1206
+ declare function collectPages<T>(http: HttpClient, spec: Omit<HttpRequestSpec, 'query'> & {
1207
+ /** Filters merged into every page request alongside `page`/`per_page`. */
1208
+ query?: HttpRequestSpec['query'];
1209
+ }, options: CollectOptions<T>): Promise<T[]>;
1210
+
1211
+ /**
1212
+ * Capabilities that mutate remote state: 12 of the 24.
1213
+ *
1214
+ * Declared as a static set rather than inferred from the HTTP verb because the
1215
+ * facade's read-only gate must be decidable before dispatch. A test asserts that
1216
+ * every entry is a real capability and that the count is exactly 12, so adding a
1217
+ * write method without registering it here fails CI.
1218
+ */
1219
+ declare const WRITE_CAPABILITIES: ReadonlySet<CapabilityId>;
1220
+ /** Returns `true` when a capability mutates remote state. */
1221
+ declare function isWriteCapability(capability: CapabilityId): boolean;
1222
+ /** Asserts a value is one of {@link PROVIDERS}. */
1223
+ declare function assertProvider(value: unknown): asserts value is Provider;
1224
+ /** Asserts a value is a non-empty trimmed string. */
1225
+ declare function assertNonEmpty(field: string, value: unknown): asserts value is string;
1226
+ /** Asserts a value is an optional non-empty string, when present. */
1227
+ declare function assertOptionalNonEmpty(field: string, value: unknown): void;
1228
+ /** Asserts a value is one of a fixed set of allowed strings. */
1229
+ declare function assertOneOf<T extends string>(field: string, value: unknown, allowed: readonly T[]): asserts value is T;
1230
+ /** Asserts a value is either a string or a number, as issue identifiers may be. */
1231
+ declare function assertNativeId(field: string, value: unknown): void;
1232
+ /** Asserts a value is a positive integer. */
1233
+ declare function assertPositiveInt(field: string, value: unknown): asserts value is number;
1234
+ /** Asserts a value is an optional positive integer, when present. */
1235
+ declare function assertOptionalPositiveInt(field: string, value: unknown): void;
1236
+ /** Asserts a value is a non-empty `{ owner, repo }` reference. */
1237
+ declare function assertRepoRef(value: unknown): void;
1238
+ /** Asserts a value is an optional array of non-empty strings. */
1239
+ declare function assertStringArray(field: string, value: unknown): void;
1240
+ /** Asserts a value is an optional non-empty array of non-empty strings. */
1241
+ declare function assertNonEmptyStringArray(field: string, value: unknown): void;
1242
+ /** Asserts a value is an organization/user login usable as a path segment. */
1243
+ declare function assertPathSegment(field: string, value: unknown): void;
1244
+ /** Asserts a file path is a relative path without traversal segments. */
1245
+ declare function assertFilePath(field: string, value: unknown): asserts value is string;
1246
+ /** Asserts a value is an optional file path. */
1247
+ declare function assertOptionalFilePath(field: string, value: unknown): void;
1248
+ /** Asserts `maxPages` is within the documented hard cap. */
1249
+ declare function assertMaxPages(value: unknown): void;
1250
+ /** Asserts a value is a plain object (used for the whole parameter bag). */
1251
+ declare function assertParamsObject(value: unknown, method: string): asserts value is object;
1252
+ /** Asserts every key of {@link CAPABILITY_IDS} is present in a candidate table. */
1253
+ declare function assertCapabilityTableKeys(table: Readonly<Record<string, unknown>>): void;
1254
+
1255
+ /**
1256
+ * Public entry of `@charles7c/git-forge`.
1257
+ *
1258
+ * Only the stable surface is exported from here: the {@link GitClient} facade,
1259
+ * models, the error type, the request layer and its helpers. Internal adapters
1260
+ * stay unexported so the public API cannot drift from the documented contract.
1261
+ */
1262
+ /** Semantic version of this build. Kept in sync with `package.json`. */
1263
+ declare const VERSION = "0.1.0";
1264
+
1265
+ export { type AuthConfig, type AuthStyle, type Branch, type BulkItemResult, type BulkOptions, CAPABILITY_IDS, type CapabilityId, type CapabilityState, type CapabilityTable, type CollectOptions, type Comment, type Commit, type CommitAuthor, type ContentEncoding, type CreateBranchParams, type CreateCommentParams, type CreateIssueParams, type CreateOrUpdateFileParams, type CreatePullRequestParams, type CreateRepositoryParams, DEFAULT_BULK_CONCURRENCY, DEFAULT_MAX_PAGES, DEFAULT_PER_PAGE, DEFAULT_RETRY_POLICY, DEFAULT_TIMEOUT_MS, DEFAULT_USER_AGENT, type DeleteFileParams, ERROR_CODES, type ErrorCode, type FileContent, type FileWriteResult, type GetCommitParams, type GetFileContentsParams, type GetIssueParams, type GetPullRequestParams, type GetRepositoryParams, GitClient, type GitClientOptions, GitForgeError, type GitForgeErrorInit, type GitForgeErrorJson, HttpClient, type HttpClientOptions, type HttpMethod, type HttpRequestSpec, type HttpResponse, type Issue, type IssueState, type ListBranchesParams, type ListCommentsParams, type ListCommitsParams, type ListIssuesParams, type ListOptions, type ListPullRequestsParams, type ListRepositoriesParams, MAX_PAGES_LIMIT, MAX_PER_PAGE, type MergeMethod, type MergePullRequestParams, type ModelIdentity, type NativeId, PARAM_CAPABILITY_IDS, PROVIDERS, type PageResult, type PageSignals, type ParamCapabilityId, type ParamCapabilityTable, type ParamsIn, type Provider, type ProviderCredentials, type ProviderParams, type PullRequest, type PullRequestRef, type PullRequestState, type PushFileAction, type PushFileEntry, type PushFilesParams, REDACTED, type RepoRef, type Repository, type RetryDecisionInput, type RetryPolicy, type UpdateIssueParams, type UserRef, VERSION, WRITE_CAPABILITIES, allSucceeded, assertCapabilityTableKeys, assertFilePath, assertMaxPages, assertNativeId, assertNonEmpty, assertNonEmptyStringArray, assertOneOf, assertOptionalFilePath, assertOptionalNonEmpty, assertOptionalPositiveInt, assertParamsObject, assertPathSegment, assertPositiveInt, assertProvider, assertRepoRef, assertStringArray, authMissingError, bulk, collectPages, computeDelay, dedupeBy, defaultRetryable, errorFromNetwork, errorFromResponse, extractRequestId, extractUpstreamMessage, invalidArgumentError, isGitForgeError, isIdempotentMethod, isRateLimitResponse, isRetryableStatus, isSensitiveKey, isWriteCapability, mapStatusToCode, normalizeMaxPages, normalizePerPage, parseLinkHeader, parseRetryAfter, partitionBulk, readTotalCount, readTotalPage, readonlyBlockedError, redactUrl, resolveNextPage, resolveRetryPolicy, retryAfterFromHeaders, retryableForStatus, scrubSecrets, shouldRetry, unsupportedCapabilityError };