@vite-hub/forge 0.0.0 → 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.
package/dist/index.js ADDED
@@ -0,0 +1,681 @@
1
+ import { a as ForgeApiError, d as NotFoundError, f as RateLimitedError, l as MergeBlockedError, n as BranchMovedError, s as ForgeTimeoutError, yt as repoRef } from "./utils-CA_4WJhJ-DNgT61X2.js";
2
+ import { defineDiagnostics } from "nostics";
3
+ import { Buffer } from "node:buffer";
4
+ import { createHash } from "node:crypto";
5
+ //#region src/env.ts
6
+ /**
7
+ * Server Env of each Forge, keyed by the `env.server.<forge>.<field>` path.
8
+ * Channels, Capabilities, Workspaces and Sources read the same names.
9
+ * `FORGES_*` names are the ones that `forgesFromEnv()` in the `forges` library reads.
10
+ * Fields without a `forges` equivalent have only a `VITEHUB_` name.
11
+ */
12
+ const forgeEnv = {
13
+ github: {
14
+ appId: { names: ["VITEHUB_GITHUB_APP_ID", "FORGES_GITHUB_APP_ID"] },
15
+ installationId: { names: ["VITEHUB_GITHUB_INSTALLATION_ID", "FORGES_GITHUB_INSTALLATION_ID"] },
16
+ appOwner: { names: ["VITEHUB_GITHUB_APP_OWNER"] },
17
+ appInstallations: { names: ["VITEHUB_GITHUB_APP_INSTALLATIONS"] },
18
+ privateKey: {
19
+ names: ["VITEHUB_GITHUB_PRIVATE_KEY", "FORGES_GITHUB_PRIVATE_KEY"],
20
+ secret: true
21
+ },
22
+ privateKeyPath: { names: ["VITEHUB_GITHUB_PRIVATE_KEY_PATH"] },
23
+ token: {
24
+ names: ["VITEHUB_GITHUB_TOKEN", "FORGES_GITHUB_TOKEN"],
25
+ secret: true
26
+ },
27
+ webhookSecret: {
28
+ names: ["VITEHUB_GITHUB_WEBHOOK_SECRET", "FORGES_GITHUB_WEBHOOK_SECRET"],
29
+ secret: true
30
+ }
31
+ },
32
+ gitlab: {
33
+ baseUrl: { names: ["VITEHUB_GITLAB_BASE_URL", "FORGES_GITLAB_BASE_URL"] },
34
+ token: {
35
+ names: ["VITEHUB_GITLAB_TOKEN", "FORGES_GITLAB_TOKEN"],
36
+ secret: true
37
+ },
38
+ webhookSecret: {
39
+ names: ["VITEHUB_GITLAB_WEBHOOK_SECRET", "FORGES_GITLAB_WEBHOOK_SECRET"],
40
+ secret: true
41
+ }
42
+ },
43
+ forgejo: {
44
+ baseUrl: { names: ["VITEHUB_FORGEJO_BASE_URL", "FORGES_FORGEJO_BASE_URL"] },
45
+ token: {
46
+ names: ["VITEHUB_FORGEJO_TOKEN", "FORGES_FORGEJO_TOKEN"],
47
+ secret: true
48
+ },
49
+ webhookSecret: {
50
+ names: ["VITEHUB_FORGEJO_WEBHOOK_SECRET", "FORGES_FORGEJO_WEBHOOK_SECRET"],
51
+ secret: true
52
+ }
53
+ }
54
+ };
55
+ /**
56
+ * The first value of `field` that is set, in its lookup order.
57
+ * `env` is a record, such as `process.env`, or a reader, such as a Cloudflare binding lookup. Default: `process.env`.
58
+ */
59
+ function readForgeEnv(field, env = globalThis.process?.env ?? {}) {
60
+ for (const name of field.names) {
61
+ const value = typeof env === "function" ? env(name) : env[name];
62
+ if (!isString(value)) continue;
63
+ const trimmed = value.trim();
64
+ if (trimmed) return trimmed;
65
+ }
66
+ }
67
+ function isString(value) {
68
+ return typeof value === "string";
69
+ }
70
+ //#endregion
71
+ //#region src/error-diagnostics.ts
72
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
73
+ const forgeDiagnostics = /*#__PURE__*/ defineDiagnostics({
74
+ docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
75
+ codes: {
76
+ /** The GitHub App installation lookup failed or the App is not installed. */
77
+ FORGE_R0001: dynamicError,
78
+ /** `forgeArchive()` was called for a Forge without archive support. */
79
+ FORGE_R0002: dynamicError,
80
+ /** `forgeGitCredentials()` received an invalid base URL or repository. */
81
+ FORGE_R0003: dynamicError,
82
+ /** `forgeBlob()` was called for a Forge without blob reads. */
83
+ FORGE_R0004: dynamicError,
84
+ /** `forgeCommitFiles()` received a file mode for a Forge without file mode writes. */
85
+ FORGE_R0005: dynamicError,
86
+ /** A GitHub-only Forge helper received a provider for another Forge. */
87
+ FORGE_R0006: dynamicError,
88
+ /** `githubBranchRuleDetails()` got branch rules that are not complete GitHub rulesets or classic protection. */
89
+ FORGE_R0007: dynamicError,
90
+ /** GitHub did not return complete review threads. */
91
+ FORGE_R0008: dynamicError,
92
+ /** A GitHub-only Forge helper received a reference that is not a numbered pull request, or an empty input. */
93
+ FORGE_R0009: dynamicError
94
+ }
95
+ });
96
+ //#endregion
97
+ //#region src/gaps/archive.ts
98
+ /**
99
+ * The repository tree at `ref` as a gzipped tarball stream.
100
+ * Gap: `forges` has no `contents.archive()`. Proposed upstream as `provider.contents.archive(repo, options)`.
101
+ */
102
+ async function forgeArchive(provider, repo, options) {
103
+ if (provider.forge !== "github") throw forgeDiagnostics.FORGE_R0002({ message: `Repository archives are not supported for ${provider.forge}.` });
104
+ const owner = encodeURIComponent(repo.owner);
105
+ const name = encodeURIComponent(repo.name);
106
+ const ref = options.ref.split("/").map(encodeURIComponent).join("/");
107
+ const path = provider.authKind === "anonymous" && provider.baseUrl.replace(/\/+$/, "") === "https://api.github.com" ? `https://codeload.github.com/${owner}/${name}/tar.gz/${ref}` : `/repos/${owner}/${name}/tarball/${ref}`;
108
+ return (await provider.request("GET", path, {
109
+ raw: true,
110
+ signal: options.signal
111
+ })).body;
112
+ }
113
+ //#endregion
114
+ //#region src/provider.ts
115
+ async function forgeProvider(connection) {
116
+ const auth = connection.token ? {
117
+ type: "token",
118
+ token: connection.token
119
+ } : { type: "anonymous" };
120
+ const options = {
121
+ ...connection.baseUrl ? { baseUrl: connection.baseUrl } : {},
122
+ ...connection.fetch ? { fetch: connection.fetch } : {},
123
+ userAgent: connection.userAgent ?? "vitehub",
124
+ ...connection.timeout === void 0 ? {} : { timeout: connection.timeout },
125
+ ...connection.readOnly === void 0 ? {} : { readOnly: connection.readOnly },
126
+ auth
127
+ };
128
+ switch (connection.forge) {
129
+ case "github": {
130
+ const { github } = await import("./github-DtncTfmv.js");
131
+ return github(options);
132
+ }
133
+ case "gitlab": {
134
+ const { gitlab } = await import("./gitlab-BoDm8-BC.js");
135
+ return gitlab(options);
136
+ }
137
+ case "forgejo": {
138
+ const { forgejo } = await import("./forgejo-BN8ItCfl.js");
139
+ return forgejo(options);
140
+ }
141
+ }
142
+ throw new Error("Unsupported Forge.");
143
+ }
144
+ /** A Forge response that succeeded but did not include the expected data. */
145
+ var ForgeResponseError = class extends Error {
146
+ name = "ForgeResponseError";
147
+ };
148
+ /** The HTTP status of a failed Forge request, or undefined for other errors. */
149
+ function forgeErrorStatus(error) {
150
+ if (!(error instanceof Error) || !("status" in error)) return void 0;
151
+ return typeof error.status === "number" ? error.status : void 0;
152
+ }
153
+ /** The error that a cancelled Forge operation rejects with. */
154
+ function abortError(signal) {
155
+ if (signal.reason instanceof Error) return signal.reason;
156
+ return new DOMException("The operation was aborted.", "AbortError");
157
+ }
158
+ /** Reject with the abort reason when `signal` aborts before `promise` settles. */
159
+ async function withSignal(promise, signal) {
160
+ if (!signal) return await promise;
161
+ if (signal.aborted) {
162
+ promise.catch(() => void 0);
163
+ throw abortError(signal);
164
+ }
165
+ return await new Promise((resolve, reject) => {
166
+ const abort = () => reject(abortError(signal));
167
+ signal.addEventListener("abort", abort, { once: true });
168
+ promise.then((value) => {
169
+ signal.removeEventListener("abort", abort);
170
+ resolve(value);
171
+ }, (error) => {
172
+ signal.removeEventListener("abort", abort);
173
+ reject(error);
174
+ });
175
+ });
176
+ }
177
+ //#endregion
178
+ //#region src/gaps/blob.ts
179
+ /**
180
+ * The bytes of one Git blob, by its sha. The blob of a symlink holds the link target.
181
+ * Gap: `forges` reads files by path only, and GitHub follows a symlink path to its target.
182
+ * Proposed upstream as `provider.contents.blob(repo, sha, options)`.
183
+ */
184
+ async function forgeBlob(provider, repo, sha, options = {}) {
185
+ if (provider.forge !== "github") throw forgeDiagnostics.FORGE_R0004({ message: `Reading a blob by sha is not supported for ${provider.forge}.` });
186
+ const { data } = await provider.request("GET", `/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}/git/blobs/${encodeURIComponent(sha)}`, { signal: options.signal });
187
+ const bytes = decodeBase64Blob(data);
188
+ if (!bytes) throw new ForgeResponseError(`GitHub returned a malformed blob ${sha}.`);
189
+ return new Uint8Array(bytes);
190
+ }
191
+ function decodeBase64Blob(value) {
192
+ if (!(value instanceof Object) || !("content" in value) || !("encoding" in value) || !("sha" in value)) return void 0;
193
+ if (typeof value.content !== "string" || value.encoding !== "base64" || typeof value.sha !== "string" || value.sha.length === 0) return void 0;
194
+ const content = value.content.replace(/\s+/g, "");
195
+ if (content.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(content)) return void 0;
196
+ try {
197
+ const bytes = Buffer.from(content, "base64");
198
+ return bytes.toString("base64") === content ? bytes : void 0;
199
+ } catch {
200
+ return;
201
+ }
202
+ }
203
+ //#endregion
204
+ //#region src/gaps/github.ts
205
+ /** Narrow a provider to GitHub, or throw `FORGE_R0006` for a GitHub-only helper. */
206
+ function requireGitHub(provider, operation) {
207
+ if (isGitHubProvider(provider)) return provider;
208
+ throw forgeDiagnostics.FORGE_R0006({ message: `${operation} is available only on GitHub. ${provider.forge} has no equivalent.` });
209
+ }
210
+ function isGitHubProvider(provider) {
211
+ return provider.forge === "github" && "graphql" in provider && typeof provider.graphql === "function";
212
+ }
213
+ function repositoryPath$1(repo) {
214
+ return `/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`;
215
+ }
216
+ function isRecord$1(value) {
217
+ return typeof value === "object" && value !== null && !Array.isArray(value);
218
+ }
219
+ //#endregion
220
+ //#region src/gaps/branch-rules.ts
221
+ const mergeMethods = {
222
+ merge: "merge",
223
+ squash: "squash",
224
+ rebase: "rebase"
225
+ };
226
+ function invalid(message) {
227
+ return forgeDiagnostics.FORGE_R0007({ message });
228
+ }
229
+ /**
230
+ * Read the GitHub-only details from the `raw` answer of `provider.repos.branchRules()`. Throws `FORGE_R0007`
231
+ * when the answer is not complete GitHub branch rules, so a caller never mistakes unknown rules for no rules.
232
+ */
233
+ function githubBranchRuleDetails(rules) {
234
+ const raw = rules.raw;
235
+ if (!isRecord$1(raw) || !isRecord$1(raw.branch) || !Array.isArray(raw.rules)) throw invalid("Branch rules are not complete GitHub branch rules.");
236
+ let requiredWorkflows = false;
237
+ let allowed;
238
+ for (const value of raw.rules) {
239
+ if (!isRecord$1(value) || typeof value.type !== "string") throw invalid("Incomplete active branch rule.");
240
+ const parameters = isRecord$1(value.parameters) ? value.parameters : void 0;
241
+ if (value.type === "required_workflows") requiredWorkflows = true;
242
+ else if (value.type === "workflows") {
243
+ if (!Array.isArray(parameters?.workflows)) throw invalid("Incomplete ruleset workflow parameters.");
244
+ requiredWorkflows ||= parameters.workflows.length > 0;
245
+ } else if (value.type === "required_status_checks") {
246
+ if (!Array.isArray(parameters?.required_status_checks)) throw invalid("Incomplete ruleset required-check parameters.");
247
+ } else if (value.type === "pull_request" && parameters?.allowed_merge_methods !== void 0) {
248
+ if (!Array.isArray(parameters.allowed_merge_methods)) throw invalid("Incomplete pull request rule merge methods.");
249
+ const rule = new Set(parameters.allowed_merge_methods.flatMap((method) => typeof method === "string" && mergeMethods[method] ? [mergeMethods[method]] : []));
250
+ allowed = allowed ? new Set([...allowed].filter((method) => rule.has(method))) : rule;
251
+ }
252
+ }
253
+ if (typeof raw.branch.protected !== "boolean") throw invalid("Branch protection summary is incomplete.");
254
+ const protection = isRecord$1(raw.branch.protection) ? raw.branch.protection : void 0;
255
+ let classicSource = "unprotected-branch";
256
+ if (raw.branch.protected === true) {
257
+ if (!protection || typeof protection.enabled !== "boolean") throw invalid("Branch protection summary is incomplete.");
258
+ if (protection.enabled !== true) throw invalid("Branch protection summary is incomplete.");
259
+ const checks = protection.required_status_checks;
260
+ if (checks !== void 0) {
261
+ if (!isRecord$1(checks) || !Array.isArray(checks.contexts) || !checks.contexts.every((context) => typeof context === "string") || checks.checks !== void 0 && !Array.isArray(checks.checks)) throw invalid("Classic protection response is ambiguous; branch summary is incomplete.");
262
+ if (checks.enforcement_level !== "everyone" && checks.enforcement_level !== "non_admins" && checks.enforcement_level !== "off") throw invalid("Classic protection response has an unsupported enforcement level.");
263
+ const bound = Array.isArray(checks.checks) ? checks.checks : [];
264
+ if (checks.enforcement_level === "off" && (checks.contexts.length > 0 || bound.length > 0)) throw invalid("Disabled classic checks contain required-check data.");
265
+ if (bound.length > 0 && (bound.some((item) => !isRecord$1(item) || typeof item.context !== "string") || checks.contexts.some((context) => !bound.some((item) => isRecord$1(item) && item.context === context)))) throw invalid("Branch summary omits required-check integration bindings.");
266
+ }
267
+ classicSource = rules.warnings?.some((warning) => warning.code === "insufficient_scope") ? "branch-summary" : "protection-endpoint";
268
+ } else if (protection !== void 0 && protection.enabled !== false) throw invalid("Branch protection summary is incomplete.");
269
+ return {
270
+ requiredWorkflows,
271
+ ...allowed ? { mergeMethods: [...allowed] } : {},
272
+ classicSource
273
+ };
274
+ }
275
+ //#endregion
276
+ //#region src/gaps/commit-files.ts
277
+ /**
278
+ * `provider.contents.commitFiles()` with Git file modes, and the sha of the new commit.
279
+ * Without a `mode`, the call goes to `commitFiles()`. When one change has a `mode`, every write without one is `100644`.
280
+ * Rejects with `BranchMovedError` when the branch no longer points at `expectedHead`, as `commitFiles()` does.
281
+ * Gap: `FileChange` has no mode, so `commitFiles()` cannot write a symlink or an executable file.
282
+ * Proposed upstream as `FileChange.mode`.
283
+ */
284
+ async function forgeCommitFiles(provider, repo, input, options = {}) {
285
+ if (input.changes.length > 0 && !input.changes.some((change) => change.mode)) return (await provider.contents.commitFiles(repo, input, options)).sha;
286
+ if (provider.forge !== "github") throw forgeDiagnostics.FORGE_R0005({ message: `Git file modes are not supported for ${provider.forge}.` });
287
+ const signal = options.signal;
288
+ const base = `/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}/git`;
289
+ const branchRef = `heads/${input.branch.split("/").map(encodeURIComponent).join("/")}`;
290
+ const readHead = async () => sha((await provider.request("GET", `${base}/ref/${branchRef}`, { signal })).data, "object", "branch");
291
+ const parent = input.createFrom === void 0 ? input.expectedHead ?? await readHead() : await provider.contents.resolveRef(repo, input.createFrom, { signal });
292
+ const baseTree = sha((await provider.request("GET", `${base}/commits/${encodeURIComponent(parent)}`, { signal })).data, "tree", "commit");
293
+ const tree = await Promise.all(input.changes.map(async (change) => {
294
+ if (change.content === null) return {
295
+ mode: change.mode ?? "100644",
296
+ path: change.path,
297
+ sha: null,
298
+ type: "blob"
299
+ };
300
+ const content = Buffer.from(change.content).toString("base64");
301
+ const blob = await provider.request("POST", `${base}/blobs`, {
302
+ body: {
303
+ content,
304
+ encoding: "base64"
305
+ },
306
+ signal
307
+ });
308
+ return {
309
+ mode: change.mode ?? "100644",
310
+ path: change.path,
311
+ sha: sha(blob.data, void 0, "blob"),
312
+ type: "blob"
313
+ };
314
+ }));
315
+ const treeSha = sha((await provider.request("POST", `${base}/trees`, {
316
+ body: {
317
+ base_tree: baseTree,
318
+ tree
319
+ },
320
+ signal
321
+ })).data, void 0, "tree");
322
+ const commit = sha((await provider.request("POST", `${base}/commits`, {
323
+ body: {
324
+ message: input.message,
325
+ parents: [parent],
326
+ tree: treeSha,
327
+ ...input.author ? { author: input.author } : {}
328
+ },
329
+ signal
330
+ })).data, void 0, "commit");
331
+ if (input.createFrom !== void 0) {
332
+ await provider.request("POST", `${base}/refs`, {
333
+ body: {
334
+ ref: `refs/heads/${input.branch}`,
335
+ sha: commit
336
+ },
337
+ signal
338
+ });
339
+ return commit;
340
+ }
341
+ try {
342
+ await provider.request("PATCH", `${base}/refs/${branchRef}`, {
343
+ body: {
344
+ force: false,
345
+ sha: commit
346
+ },
347
+ signal
348
+ });
349
+ } catch (error) {
350
+ const status = forgeErrorStatus(error);
351
+ if (status !== 409 && status !== 422) throw error;
352
+ const head = await readHead();
353
+ if (head === parent) throw error;
354
+ throw new BranchMovedError(`${input.branch} is at ${head}, not ${parent}`, status, "", {
355
+ forge: provider.forge,
356
+ instance: provider.instance
357
+ }, { cause: error });
358
+ }
359
+ return commit;
360
+ }
361
+ /** The `sha` of a GitHub Git database response, or of its `key` object. */
362
+ function sha(value, key, description) {
363
+ const target = key && value instanceof Object && key in value ? Reflect.get(value, key) : value;
364
+ const result = target instanceof Object && "sha" in target ? target.sha : void 0;
365
+ if (typeof result !== "string" || !result) throw new ForgeResponseError(`GitHub returned a malformed ${description} response.`);
366
+ return result;
367
+ }
368
+ //#endregion
369
+ //#region src/gaps/git-credentials.ts
370
+ const defaultInstance = {
371
+ github: "https://github.com",
372
+ gitlab: "https://gitlab.com",
373
+ forgejo: "https://codeberg.org"
374
+ };
375
+ const tokenUsername = {
376
+ github: "x-access-token",
377
+ gitlab: "oauth2",
378
+ forgejo: "oauth2"
379
+ };
380
+ function instanceRoot(forge, baseUrl) {
381
+ if (!baseUrl) return defaultInstance[forge];
382
+ const url = new URL(baseUrl);
383
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw forgeDiagnostics.FORGE_R0003({ message: `Forge base URL ${JSON.stringify(baseUrl)} must use http or https.` });
384
+ let path = url.pathname.replace(/\/+$/, "");
385
+ if (forge === "github") {
386
+ if (url.hostname === "api.github.com") return defaultInstance.github;
387
+ path = path.replace(/\/api\/v3$/, "");
388
+ }
389
+ return `${url.origin}${path}`;
390
+ }
391
+ function repositoryPath(repository) {
392
+ const segments = repository.replace(/\.git$/, "").split("/");
393
+ if (segments.length < 2 || segments.some((segment) => !segment || segment === "." || segment === ".." || /[\s\\?#%]/.test(segment))) throw forgeDiagnostics.FORGE_R0003({ message: `Repository ${JSON.stringify(repository)} must be owner/name.` });
394
+ return segments.map(encodeURIComponent).join("/");
395
+ }
396
+ /**
397
+ * Git smart HTTP remote and credentials for one repository.
398
+ * Gap: `forges` exposes `Repo.cloneUrls` but no transport credential.
399
+ */
400
+ function forgeGitCredentials(input) {
401
+ const url = `${instanceRoot(input.forge, input.baseUrl)}/${repositoryPath(input.repository)}.git`;
402
+ if (!input.token) return { url };
403
+ return {
404
+ url,
405
+ username: tokenUsername[input.forge],
406
+ password: input.token
407
+ };
408
+ }
409
+ /**
410
+ * The `http.<url>.extraheader` config entry that sends the credentials to the remote only.
411
+ * Pass it through `GIT_CONFIG_KEY_<n>` and `GIT_CONFIG_VALUE_<n>`, not `-c`, so the token is not in process arguments.
412
+ * Undefined for anonymous credentials.
413
+ */
414
+ function forgeGitAuthHeader(credentials) {
415
+ if (!credentials.password) return void 0;
416
+ const basic = Buffer.from(`${credentials.username ?? ""}:${credentials.password}`).toString("base64");
417
+ return {
418
+ key: `http.${credentials.url}.extraheader`,
419
+ value: `AUTHORIZATION: basic ${basic}`
420
+ };
421
+ }
422
+ //#endregion
423
+ //#region src/gaps/retarget.ts
424
+ /** Change the base branch of a GitHub pull request. */
425
+ async function retargetPullRequest(provider, thread, base, options) {
426
+ requireGitHub(provider, "retargetPullRequest()");
427
+ if (thread.kind !== "pull_request" || !thread.number) throw forgeDiagnostics.FORGE_R0009({ message: "Only a pull request with a number can change its base branch." });
428
+ if (!base.trim()) throw forgeDiagnostics.FORGE_R0009({ message: "The new base branch must not be empty." });
429
+ await provider.request("PATCH", `${repositoryPath$1(thread.repo)}/pulls/${encodeURIComponent(thread.number)}`, {
430
+ body: { base },
431
+ signal: options?.signal
432
+ });
433
+ }
434
+ //#endregion
435
+ //#region src/gaps/review-threads.ts
436
+ const THREADS = `query ForgeReviewThreads($owner:String!,$name:String!,$number:Int!,$after:String) {
437
+ repository(owner:$owner,name:$name) { pullRequest(number:$number) { reviewThreads(first:100,after:$after) {
438
+ nodes { id isResolved isOutdated path line originalLine startLine originalStartLine
439
+ comments(first:100) { nodes { id databaseId } pageInfo { hasNextPage endCursor } }
440
+ } pageInfo { hasNextPage endCursor }
441
+ } } }
442
+ }`;
443
+ const THREAD_COMMENTS = `query ForgeReviewThreadComments($id:ID!,$after:String!) {
444
+ node(id:$id) { ... on PullRequestReviewThread { comments(first:100,after:$after) {
445
+ nodes { id databaseId } pageInfo { hasNextPage endCursor }
446
+ } } }
447
+ }`;
448
+ const THREAD = `query ForgeReviewThread($id:ID!) {
449
+ node(id:$id) { ... on PullRequestReviewThread { id isResolved pullRequest { id } } }
450
+ }`;
451
+ async function graphql(provider, query, variables, options) {
452
+ const operationName = /\b(?:query|mutation)\s+([A-Za-z0-9_]+)/.exec(query)?.[1];
453
+ const response = await provider.request("POST", "/graphql", {
454
+ body: {
455
+ query,
456
+ variables,
457
+ ...operationName ? { operationName } : {}
458
+ },
459
+ signal: options?.signal
460
+ });
461
+ const payload = isRecord$1(response.data) ? response.data : void 0;
462
+ const errors = payload?.errors;
463
+ if (Array.isArray(errors) && errors.length) throw incomplete(`GitHub review thread query failed: ${errors.map((error) => isRecord$1(error) && typeof error.message === "string" ? error.message : String(error)).join("; ")}`);
464
+ return payload?.data ?? response.data;
465
+ }
466
+ function incomplete(message) {
467
+ return forgeDiagnostics.FORGE_R0008({ message });
468
+ }
469
+ function field(value, ...path) {
470
+ let current = value;
471
+ for (const key of path) current = isRecord$1(current) ? current[key] : void 0;
472
+ return current;
473
+ }
474
+ function connection(value) {
475
+ const page = field(value, "pageInfo");
476
+ const nodes = field(value, "nodes");
477
+ if (!Array.isArray(nodes) || !isRecord$1(page) || typeof page.hasNextPage !== "boolean") throw incomplete("GitHub returned an incomplete review thread page.");
478
+ const endCursor = typeof page.endCursor === "string" && page.endCursor ? page.endCursor : void 0;
479
+ if (page.hasNextPage && !endCursor) throw incomplete("GitHub omitted a review thread cursor.");
480
+ return {
481
+ nodes,
482
+ hasNextPage: page.hasNextPage,
483
+ ...endCursor ? { endCursor } : {}
484
+ };
485
+ }
486
+ function advance(page, seen) {
487
+ if (!page.hasNextPage) return void 0;
488
+ if (seen.has(page.endCursor)) throw incomplete("GitHub repeated a review thread cursor.");
489
+ seen.add(page.endCursor);
490
+ return page.endCursor;
491
+ }
492
+ function comment(value) {
493
+ if (!isRecord$1(value) || typeof value.id !== "string") throw incomplete("GitHub returned an incomplete review comment.");
494
+ return {
495
+ id: value.id,
496
+ ...typeof value.databaseId === "number" ? { restId: String(value.databaseId) } : {}
497
+ };
498
+ }
499
+ function optionalNumber(value) {
500
+ return typeof value === "number" ? value : void 0;
501
+ }
502
+ /** List every review conversation of a GitHub pull request, with the identity of every comment in it. */
503
+ async function listReviewThreads(provider, thread, options) {
504
+ requireGitHub(provider, "listReviewThreads()");
505
+ if (thread.kind !== "pull_request" || !thread.number) throw forgeDiagnostics.FORGE_R0009({ message: "Review threads belong to a pull request with a number." });
506
+ const threads = [];
507
+ const pages = /* @__PURE__ */ new Set();
508
+ let after;
509
+ do {
510
+ const page = connection(field(await graphql(provider, THREADS, {
511
+ owner: thread.repo.owner,
512
+ name: thread.repo.name,
513
+ number: Number(thread.number),
514
+ after: after ?? null
515
+ }, options), "repository", "pullRequest", "reviewThreads"));
516
+ after = advance(page, pages);
517
+ for (const node of page.nodes) {
518
+ if (!isRecord$1(node) || typeof node.id !== "string" || typeof node.isResolved !== "boolean") throw incomplete("GitHub returned incomplete review thread metadata.");
519
+ const first = connection(node.comments);
520
+ const comments = first.nodes.map(comment);
521
+ const commentPages = /* @__PURE__ */ new Set();
522
+ let commentAfter = advance(first, commentPages);
523
+ while (commentAfter) {
524
+ const more = connection(field(await graphql(provider, THREAD_COMMENTS, {
525
+ id: node.id,
526
+ after: commentAfter
527
+ }, options), "node", "comments"));
528
+ comments.push(...more.nodes.map(comment));
529
+ commentAfter = advance(more, commentPages);
530
+ }
531
+ const { comments: _comments, ...raw } = node;
532
+ threads.push({
533
+ id: node.id,
534
+ resolved: node.isResolved,
535
+ outdated: node.isOutdated === true,
536
+ path: typeof node.path === "string" ? node.path : void 0,
537
+ line: optionalNumber(node.line),
538
+ startLine: optionalNumber(node.startLine),
539
+ originalLine: optionalNumber(node.originalLine),
540
+ originalStartLine: optionalNumber(node.originalStartLine),
541
+ comments,
542
+ raw
543
+ });
544
+ }
545
+ } while (after);
546
+ return threads;
547
+ }
548
+ /** Look up one review conversation by its id. Returns undefined when the id names no review conversation. */
549
+ async function getReviewThread(provider, id, options) {
550
+ requireGitHub(provider, "getReviewThread()");
551
+ const node = field(await graphql(provider, THREAD, { id }, options), "node");
552
+ if (node === null || isRecord$1(node) && Object.keys(node).length === 0) return void 0;
553
+ const pullRequestId = field(node, "pullRequest", "id");
554
+ if (!isRecord$1(node) || typeof node.id !== "string" || typeof node.isResolved !== "boolean" || typeof pullRequestId !== "string") throw incomplete("GitHub returned an incomplete review thread.");
555
+ return {
556
+ id: node.id,
557
+ resolved: node.isResolved,
558
+ pullRequestId
559
+ };
560
+ }
561
+ //#endregion
562
+ //#region src/github-app.ts
563
+ const appProviders = /* @__PURE__ */ new Map();
564
+ const installationTokens = /* @__PURE__ */ new WeakMap();
565
+ const appProviderLimit = 128;
566
+ const fetchIds = /* @__PURE__ */ new WeakMap();
567
+ let nextFetchId = 0;
568
+ function fetchId(fetcher) {
569
+ if (!fetcher) return 0;
570
+ let id = fetchIds.get(fetcher);
571
+ if (id === void 0) {
572
+ id = ++nextFetchId;
573
+ fetchIds.set(fetcher, id);
574
+ }
575
+ return id;
576
+ }
577
+ function appProviderKey(input, installationId) {
578
+ return createHash("sha256").update(`${input.baseUrl || "https://api.github.com"}\0${input.appId}\0${input.privateKey}\0${input.userAgent ?? ""}\0${fetchId(input.fetch)}\0${installationId}`).digest("hex");
579
+ }
580
+ /**
581
+ * One App provider per installation, so `refresh` replaces the token of that installation only.
582
+ * App-level requests use the entry with an empty installation ID.
583
+ */
584
+ function appProvider(input, installationId = "", refresh = false) {
585
+ const key = appProviderKey(input, installationId);
586
+ if (refresh) appProviders.delete(key);
587
+ const cached = appProviders.get(key);
588
+ if (cached) return cached;
589
+ const pending = import("./github-DtncTfmv.js").then(({ github }) => github({
590
+ ...input.baseUrl ? { baseUrl: input.baseUrl } : {},
591
+ ...input.fetch ? { fetch: input.fetch } : {},
592
+ userAgent: input.userAgent ?? "vitehub",
593
+ auth: {
594
+ type: "app",
595
+ appId: input.appId,
596
+ privateKey: input.privateKey
597
+ }
598
+ }));
599
+ pending.catch(() => appProviders.delete(key));
600
+ appProviders.set(key, pending);
601
+ if (appProviders.size > appProviderLimit) appProviders.delete(appProviders.keys().next().value);
602
+ return pending;
603
+ }
604
+ function isRecord(value) {
605
+ return typeof value === "object" && value !== null && !Array.isArray(value);
606
+ }
607
+ function positiveId(value) {
608
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
609
+ }
610
+ /**
611
+ * GitHub App credentials. App providers are cached per API base, App, private key, user agent,
612
+ * fetch function, and installation, so installation tokens are minted once and reused until they expire.
613
+ */
614
+ function githubAppCredentials(input) {
615
+ return {
616
+ async installationToken(installationId, options = {}) {
617
+ const id = String(installationId);
618
+ const provider = await withSignal(appProvider(input, id, options.refresh), options.signal);
619
+ const cached = installationTokens.get(provider);
620
+ if (cached && cached.expiresAt > Date.now() + 6e4) return {
621
+ token: cached.token,
622
+ expiresAt: new Date(cached.expiresAt)
623
+ };
624
+ const response = await withSignal(provider.request("POST", `/app/installations/${id}/access_tokens`, { signal: options.signal }), options.signal);
625
+ if (!response.data.token) throw new ForgeResponseError("GitHub App installation token response did not include token.");
626
+ const details = {
627
+ token: response.data.token,
628
+ expiresAt: new Date(response.data.expires_at)
629
+ };
630
+ installationTokens.set(provider, {
631
+ token: details.token,
632
+ expiresAt: details.expiresAt.getTime()
633
+ });
634
+ return details;
635
+ },
636
+ async installation(repository, signal) {
637
+ const provider = await withSignal(appProvider(input), signal);
638
+ const path = `/repos/${repository}/installation`;
639
+ try {
640
+ const response = await provider.request("GET", path, { signal });
641
+ const id = positiveId(isRecord(response.data) ? response.data.id : void 0);
642
+ if (!id) throw forgeDiagnostics.FORGE_R0001({ message: `GitHub App is not installed for ${repository}.` });
643
+ return id;
644
+ } catch (error) {
645
+ if (signal?.aborted) throw abortError(signal);
646
+ const status = forgeErrorStatus(error);
647
+ if (status === void 0) throw error;
648
+ throw forgeDiagnostics.FORGE_R0001({
649
+ message: `GitHub App request ${path} failed with ${status}.`,
650
+ cause: error
651
+ });
652
+ }
653
+ },
654
+ async app(signal) {
655
+ const response = await (await withSignal(appProvider(input), signal)).request("GET", "/app", { signal });
656
+ const id = positiveId(isRecord(response.data) ? response.data.id : void 0);
657
+ const slug = isRecord(response.data) && typeof response.data.slug === "string" ? response.data.slug : void 0;
658
+ if (!id) throw new ForgeResponseError("GitHub App metadata did not include an ID.");
659
+ if (!slug) throw new ForgeResponseError("GitHub App response did not include a slug.");
660
+ return {
661
+ id,
662
+ slug,
663
+ login: `${slug}[bot]`
664
+ };
665
+ }
666
+ };
667
+ }
668
+ /** Read a GitHub App private key from an inline value or a file path. Escaped "\\n" becomes a newline. */
669
+ async function readGitHubAppPrivateKey(inline, path) {
670
+ const value = inline?.trim();
671
+ if (value) return value.replace(/\\n/g, "\n");
672
+ if (!path) return void 0;
673
+ const { readFile } = await import(
674
+ /* @vite-ignore */
675
+ "node:fs/promises"
676
+ );
677
+ const file = (await readFile(path, "utf8")).trim();
678
+ return file ? file.replace(/\\n/g, "\n") : void 0;
679
+ }
680
+ //#endregion
681
+ export { BranchMovedError, ForgeApiError, ForgeResponseError, ForgeTimeoutError, MergeBlockedError, NotFoundError, RateLimitedError, abortError, forgeArchive, forgeBlob, forgeCommitFiles, forgeEnv, forgeErrorStatus, forgeGitAuthHeader, forgeGitCredentials, forgeProvider, getReviewThread, githubAppCredentials, githubBranchRuleDetails, listReviewThreads, readForgeEnv, readGitHubAppPrivateKey, repoRef, retargetPullRequest, withSignal };