@fabrika/github-app 0.9.0-dev.1 → 0.9.0-dev.10

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/github-app",
3
- "version": "0.9.0-dev.1",
3
+ "version": "0.9.0-dev.10",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -9,12 +9,13 @@
9
9
  },
10
10
  "files": [
11
11
  "src",
12
- "!src/**/__tests__/**"
12
+ "!src/**/__tests__/**",
13
+ "types"
13
14
  ],
14
15
  "exports": {
15
16
  ".": {
16
17
  "bun": "./src/index.ts",
17
- "types": "./src/index.ts",
18
+ "types": "./types/src/index.d.ts",
18
19
  "default": "./src/index.ts"
19
20
  }
20
21
  },
package/src/client.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { configurationError, requestStatusError, responseError } from './errors'
1
+ import { configurationError, GitHubRateLimitError, requestStatusError, responseError } from './errors'
2
2
  import { createRepositoryClient } from './repository'
3
3
  import type { GitHubRepositoryClient, GitHubRepositoryOpenRequest } from './repository-types'
4
4
  import { pemToPkcs8, signAppJwt } from './signing'
5
- import { createCancellation, GITHUB_ACCEPT, GITHUB_API_VERSION, GITHUB_USER_AGENT, readBoundedJson } from './transport'
5
+ import { createCancellation, GITHUB_ACCEPT, GITHUB_API_VERSION, GITHUB_USER_AGENT, pause, readBoundedJson } from './transport'
6
6
  import type {
7
7
  GitHubAppClientConfig,
8
8
  GitHubAppFetch,
@@ -26,6 +26,12 @@ import {
26
26
  validateWebhookSecret,
27
27
  } from './validation'
28
28
 
29
+ /** The most anonymous reads of the App's public page a client may make before a rate limit is the caller's answer. */
30
+ const MAX_PUBLIC_APP_ATTEMPTS = 4
31
+ /** The wait before the next anonymous read when GitHub names none; it doubles with each read. */
32
+ const PUBLIC_APP_BACKOFF_MS = 500
33
+ /** A `retry-after` longer than this is GitHub's answer: the read is not tried again. */
34
+ const MAX_PUBLIC_APP_WAIT_MS = 5_000
29
35
  const DEFAULT_API_BASE_URL = 'https://api.github.com'
30
36
  const DEFAULT_REQUEST_TIMEOUT_MS = 15_000
31
37
  const MAX_REQUEST_TIMEOUT_MS = 120_000
@@ -41,6 +47,7 @@ export class GitHubAppClient {
41
47
  private readonly fetchImplementation: GitHubAppFetch,
42
48
  private readonly clock: () => number,
43
49
  private readonly timeoutMs: number,
50
+ private readonly publicAppAttempts: number,
44
51
  ) {}
45
52
 
46
53
  /** Validate all configuration and import the RSA key before a credential-owning service boots. */
@@ -53,6 +60,10 @@ export class GitHubAppClient {
53
60
  if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_REQUEST_TIMEOUT_MS) {
54
61
  throw configurationError()
55
62
  }
63
+ const publicAppAttempts = config.publicAppAttempts ?? 1
64
+ if (!Number.isSafeInteger(publicAppAttempts) || publicAppAttempts < 1 || publicAppAttempts > MAX_PUBLIC_APP_ATTEMPTS) {
65
+ throw configurationError()
66
+ }
56
67
  let privateKey: CryptoKey
57
68
  try {
58
69
  privateKey = await crypto.subtle.importKey(
@@ -65,7 +76,10 @@ export class GitHubAppClient {
65
76
  } catch {
66
77
  throw configurationError()
67
78
  }
68
- return new GitHubAppClient(config.appId, privateKey, apiBaseUrl, config.fetch ?? fetch, config.now ?? Date.now, timeoutMs)
79
+ // The global `fetch` is wrapped: a Worker refuses it with any other `this` ("Illegal invocation"), and the client calls
80
+ // it as its own property, and hands it to the repository client.
81
+ const fetchImplementation = config.fetch ?? ((input, init) => fetch(input, init))
82
+ return new GitHubAppClient(config.appId, privateKey, apiBaseUrl, fetchImplementation, config.now ?? Date.now, timeoutMs, publicAppAttempts)
69
83
  }
70
84
 
71
85
  /** Read and bind the public identity represented by this client's App credentials. */
@@ -74,13 +88,31 @@ export class GitHubAppClient {
74
88
  if (body === NOT_FOUND) throw responseError()
75
89
  const identity = decodeAppIdentity(body)
76
90
  if (identity === null || String(identity.id) !== this.appId) throw responseError()
77
- const publicBody = await this.requestJson(`/apps/${identity.slug}`, {}, signal, true, false)
91
+ const publicBody = await this.publicApp(identity.slug, signal)
78
92
  if (publicBody === NOT_FOUND) return { ...identity, public: false }
79
93
  const publicIdentity = decodeAppIdentity(publicBody)
80
94
  if (publicIdentity === null || !sameAppIdentity(identity, publicIdentity)) throw responseError()
81
95
  return { ...identity, public: true }
82
96
  }
83
97
 
98
+ /**
99
+ * The App's public page, read without credentials: GitHub answers it only for a public App. The read is anonymous,
100
+ * so it spends the caller's address's limit. Where the next read may leave from another address (a Worker on a cloud's
101
+ * shared egress), the client is configured to try a rate-limited read again after a short wait.
102
+ */
103
+ private async publicApp(slug: string, signal?: AbortSignal): Promise<unknown | typeof NOT_FOUND> {
104
+ for (let attempt = 1;; attempt++) {
105
+ try {
106
+ return await this.requestJson(`/apps/${slug}`, {}, signal, true, false)
107
+ } catch (error) {
108
+ if (!(error instanceof GitHubRateLimitError) || attempt >= this.publicAppAttempts) throw error
109
+ const wait = error.retryAfterMs ?? PUBLIC_APP_BACKOFF_MS * 2 ** (attempt - 1)
110
+ if (wait > MAX_PUBLIC_APP_WAIT_MS) throw error
111
+ await pause(wait, signal)
112
+ }
113
+ }
114
+ }
115
+
84
116
  /** Read the App webhook transport settings without exposing GitHub's masked secret field. */
85
117
  async getWebhookConfig(signal?: AbortSignal): Promise<GitHubAppWebhookConfig> {
86
118
  const body = await this.requestJson('/app/hook/config', {}, signal, false)
@@ -224,7 +256,8 @@ export class GitHubAppClient {
224
256
  response = await this.fetchImplementation(`${this.apiBaseUrl}${path}`, {
225
257
  ...init,
226
258
  headers,
227
- redirect: 'error',
259
+ // Workers refuse `redirect: 'error'`; a redirect is a response that is not `ok` and fails below.
260
+ redirect: 'manual',
228
261
  signal: cancellation.signal,
229
262
  })
230
263
  } catch {
@@ -236,7 +269,9 @@ export class GitHubAppClient {
236
269
  return NOT_FOUND
237
270
  }
238
271
  if (!response.ok) {
239
- throw requestStatusError(response.status)
272
+ // An unread body holds its connection open on workerd, and a retried read would hold another.
273
+ void response.body?.cancel().catch(() => {})
274
+ throw requestStatusError(response.status, response.headers, !authenticate, () => this.now())
240
275
  }
241
276
  return await readBoundedJson(response, cancellation)
242
277
  } finally {
package/src/errors.ts CHANGED
@@ -10,8 +10,42 @@ export class GitHubRequestError extends Error {
10
10
  }
11
11
  }
12
12
 
13
- export function requestStatusError(status: number): GitHubRequestError {
14
- return new GitHubRequestError(status)
13
+ /**
14
+ * GitHub refused a request for its rate limit: a 429, or a 403 that says the limit is spent (`x-ratelimit-remaining: 0`)
15
+ * or when to come back (`retry-after`, GitHub's secondary limit). An anonymous read spends the caller's address's limit,
16
+ * which every tenant of a cloud's shared egress spends with it.
17
+ */
18
+ export class GitHubRateLimitError extends GitHubRequestError {
19
+ constructor(
20
+ status: number,
21
+ readonly anonymous: boolean,
22
+ /** When GitHub admits the next request: `retry-after` when it sends one, else `x-ratelimit-reset`. */
23
+ readonly resetAt: Date | undefined,
24
+ /** GitHub's `retry-after`, in milliseconds; only the secondary limit sends it. */
25
+ readonly retryAfterMs: number | undefined,
26
+ ) {
27
+ super(status)
28
+ this.name = 'GitHubRateLimitError'
29
+ }
30
+ }
31
+
32
+ export function requestStatusError(
33
+ status: number,
34
+ headers?: Headers,
35
+ anonymous = false,
36
+ now: () => number = Date.now,
37
+ ): GitHubRequestError {
38
+ const retryAfter = headers?.get('retry-after') ?? null
39
+ const limited = status === 429 || (status === 403 && (headers?.get('x-ratelimit-remaining') === '0' || retryAfter !== null))
40
+ if (!limited) return new GitHubRequestError(status)
41
+ const retryAfterMs = retryAfter !== null && /^\d{1,6}$/.test(retryAfter) ? Number(retryAfter) * 1000 : undefined
42
+ const reset = headers?.get('x-ratelimit-reset') ?? null
43
+ const resetAt = retryAfterMs !== undefined
44
+ ? new Date(now() + retryAfterMs)
45
+ : reset !== null && /^\d{1,12}$/.test(reset)
46
+ ? new Date(Number(reset) * 1000)
47
+ : undefined
48
+ return new GitHubRateLimitError(status, anonymous, resetAt, retryAfterMs)
15
49
  }
16
50
 
17
51
  export function responseError(): Error {
package/src/index.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { GitHubAppClient } from './client'
2
- export { GitHubBranchConflictError, GitHubNotFoundError, GitHubRequestError, GitHubStaleHeadError } from './errors'
2
+ export { GitHubBranchConflictError, GitHubNotFoundError, GitHubRateLimitError, GitHubRequestError, GitHubStaleHeadError } from './errors'
3
3
  export { buildGitHubAppManifest, exchangeGitHubAppManifestCode } from './manifest'
4
4
  export type {
5
5
  GitHubBlobRead,
package/src/manifest.ts CHANGED
@@ -57,7 +57,8 @@ export async function exchangeGitHubAppManifestCode(
57
57
  'user-agent': GITHUB_MANIFEST_USER_AGENT,
58
58
  'x-github-api-version': GITHUB_API_VERSION,
59
59
  },
60
- redirect: 'error',
60
+ // Workers refuse `redirect: 'error'`; a redirect is a response that is not `ok` and fails below.
61
+ redirect: 'manual',
61
62
  signal: cancellation.signal,
62
63
  },
63
64
  )
@@ -66,7 +67,10 @@ export async function exchangeGitHubAppManifestCode(
66
67
  throw new Error('GitHub App manifest conversion failed')
67
68
  }
68
69
  cancellation.throwIfCancelled()
69
- if (!response.ok) throw new Error('GitHub App manifest conversion failed')
70
+ if (!response.ok) {
71
+ void response.body?.cancel().catch(() => {})
72
+ throw new Error('GitHub App manifest conversion failed')
73
+ }
70
74
  const app = decodeManifestConversion(await readManifestConversionJson(response, cancellation))
71
75
  if (app === null) throw new Error('GitHub App manifest conversion returned an invalid response')
72
76
  return app
@@ -109,6 +113,7 @@ async function readManifestConversionJson(response: Response, cancellation: Mani
109
113
  cancellation.throwIfCancelled()
110
114
  const contentLength = response.headers.get('content-length')
111
115
  if (contentLength !== null && /^[0-9]+$/.test(contentLength) && Number(contentLength) > MAX_MANIFEST_CONVERSION_BYTES) {
116
+ void response.body?.cancel().catch(() => {})
112
117
  throw new Error('GitHub App manifest conversion returned an invalid response')
113
118
  }
114
119
  const reader = response.body?.getReader()
@@ -106,9 +106,10 @@ export interface DecodedTree {
106
106
  readonly truncated: boolean
107
107
  }
108
108
 
109
- export function decodeTree(body: unknown, expectedSha: string): DecodedTree {
109
+ /** A tree read by `<commit>:<path>`, whose own sha the request did not name. */
110
+ export function decodeTreeListing(body: unknown): DecodedTree {
110
111
  const result = treeSchema.safeParse(body)
111
- if (!result.success || result.data.sha !== expectedSha) throw responseError()
112
+ if (!result.success) throw responseError()
112
113
  return { entries: result.data.tree, truncated: result.data.truncated }
113
114
  }
114
115
 
package/src/repository.ts CHANGED
@@ -21,11 +21,12 @@ import {
21
21
  decodeCommit,
22
22
  decodeComparison,
23
23
  decodeCreatedTreeSha,
24
+ type DecodedTree,
24
25
  decodePullRequest,
25
26
  decodePullRequestList,
26
27
  decodeRef,
27
28
  decodeTextBlob,
28
- decodeTree,
29
+ decodeTreeListing,
29
30
  encodeBranch,
30
31
  MAX_BLOB_RESPONSE_BYTES,
31
32
  MAX_CHANGED_BYTES,
@@ -89,6 +90,8 @@ export function createRepositoryClient(config: RepositoryClientConfig): GitHubRe
89
90
 
90
91
  class RepositoryClient implements GitHubRepositoryClient {
91
92
  readonly #config: RepositoryClientConfig
93
+ /** Commits and trees this client read, by request path: a sha names immutable content, so one client reads each once. */
94
+ readonly #objects = new Map<string, Promise<unknown>>()
92
95
 
93
96
  constructor(config: RepositoryClientConfig) {
94
97
  this.#config = config
@@ -103,41 +106,36 @@ class RepositoryClient implements GitHubRepositoryClient {
103
106
  async readTree(commitSha: string, directory = '', signal?: AbortSignal): Promise<GitHubTreeListing> {
104
107
  validateSha(commitSha)
105
108
  if (directory !== '') validatePath(directory)
106
- const rootSha = (await this.#readCommit(commitSha, signal)).treeSha
107
- let treeSha = rootSha
108
- if (directory !== '') {
109
- const entry = await this.#treeWalker(rootSha, signal).find(directory)
110
- if (entry?.type !== 'tree') return { commitSha, directory, entries: [], truncated: false }
111
- treeSha = entry.sha
112
- }
113
- const tree = decodeTree(await this.#readGitObject(`/git/trees/${treeSha}?recursive=1`, signal, MAX_TREE_RESPONSE_BYTES), treeSha)
109
+ const listing = await this.#readTreeAt(commitSha, directory, '?recursive=1', signal)
110
+ if (listing === null) return { commitSha, directory, entries: [], truncated: false }
114
111
  const prefix = directory === '' ? '' : `${directory}/`
115
- const entries = tree.entries.slice(0, MAX_TREE_ENTRIES).map((entry) => ({ ...entry, path: `${prefix}${entry.path}` }))
116
- return { commitSha, directory, entries, truncated: tree.truncated || tree.entries.length > MAX_TREE_ENTRIES }
112
+ const entries = listing.entries.slice(0, MAX_TREE_ENTRIES).map((entry) => ({ ...entry, path: `${prefix}${entry.path}` }))
113
+ return { commitSha, directory, entries, truncated: listing.truncated || listing.entries.length > MAX_TREE_ENTRIES }
117
114
  }
118
115
 
119
116
  async readFiles(commitSha: string, paths: readonly string[], signal?: AbortSignal): Promise<GitHubFileRead> {
120
117
  validateSha(commitSha)
121
118
  if (paths.length === 0 || paths.length > MAX_READ_PATHS || new Set(paths).size !== paths.length) throw configurationError()
122
119
  for (const path of paths) validatePath(path)
123
- const directories = this.#treeWalker((await this.#readCommit(commitSha, signal)).treeSha, signal)
120
+ const entries = await Promise.all(paths.map((path) => this.#find(commitSha, path, signal)))
121
+ const blobs: GitHubBlobRef[] = []
122
+ const notFiles = new Map<string, GitHubUnreadableReason>()
123
+ for (const [index, path] of paths.entries()) {
124
+ const entry = entries[index] ?? null
125
+ if (entry === null) notFiles.set(path, 'missing')
126
+ else if (entry.type !== 'blob' || entry.mode === '120000') notFiles.set(path, 'not_a_file')
127
+ else blobs.push({ path, sha: entry.sha, size: entry.size })
128
+ }
129
+ const read = blobs.length === 0 ? { files: [], unreadable: [] } : await this.readBlobTexts(blobs, signal)
130
+ const reasons = new Map([...notFiles, ...read.unreadable.map((entry): [string, GitHubUnreadableReason] => [entry.path, entry.reason])])
131
+ const contents = new Map(read.files.map((file) => [file.path, file.content]))
124
132
  const files: GitHubTextFile[] = []
125
133
  const unreadable: GitHubUnreadablePath[] = []
126
- let remainingBytes = MAX_READ_BYTES
127
134
  for (const path of paths) {
128
- const entry = readableBlob(await directories.find(path), remainingBytes)
129
- if (typeof entry === 'string') {
130
- unreadable.push({ path, reason: entry })
131
- continue
132
- }
133
- const body = await this.#readGitObject(`/git/blobs/${entry.sha}`, signal, MAX_BLOB_RESPONSE_BYTES)
134
- const content = decodeTextBlob(body, entry.sha, entry.size)
135
- if (content === null) {
136
- unreadable.push({ path, reason: 'binary' })
137
- continue
138
- }
139
- remainingBytes -= entry.size
140
- files.push({ path, content })
135
+ const content = contents.get(path)
136
+ const reason = reasons.get(path)
137
+ if (content !== undefined) files.push({ path, content })
138
+ else if (reason !== undefined) unreadable.push({ path, reason })
141
139
  }
142
140
  return { commitSha, files, unreadable }
143
141
  }
@@ -230,10 +228,12 @@ class RepositoryClient implements GitHubRepositoryClient {
230
228
  const changes = treeChanges(input.changes)
231
229
 
232
230
  // Known limit: REST has no compare-and-swap, so a concurrent reset to an ancestor still lets the non-force PATCH fast-forward.
231
+ const parentRead = this.#readCommit(input.expectedHeadSha, input.signal)
232
+ parentRead.catch(() => undefined)
233
233
  const head = await this.readRef(input.branch, input.signal)
234
234
  if (head?.sha !== input.expectedHeadSha) throw new GitHubStaleHeadError()
235
- const parent = await this.#readCommit(input.expectedHeadSha, input.signal)
236
- const tree = await this.#resolveModes(changes, parent.treeSha, input.signal)
235
+ const parent = await parentRead
236
+ const tree = await this.#resolveModes(changes, parent.sha, input.signal)
237
237
 
238
238
  const createdTree = await this.#request('/git/trees', {
239
239
  method: 'POST',
@@ -295,20 +295,40 @@ class RepositoryClient implements GitHubRepositoryClient {
295
295
  }
296
296
 
297
297
  /** Keeps an edited executable's mode, and refuses to delete anything but an existing file. */
298
- async #resolveModes(changes: readonly TreeChange[], rootSha: string, signal: AbortSignal | undefined): Promise<TreeChange[]> {
299
- const head = this.#treeWalker(rootSha, signal)
300
- const result: TreeChange[] = []
301
- for (const change of changes) {
302
- const existing = await head.find(change.path)
303
- const isFile = existing?.type === 'blob'
298
+ async #resolveModes(changes: readonly TreeChange[], commitSha: string, signal: AbortSignal | undefined): Promise<TreeChange[]> {
299
+ const existing = await Promise.all(changes.map((change) => this.#find(commitSha, change.path, signal)))
300
+ return changes.map((change, index) => {
301
+ const entry = existing[index] ?? null
302
+ const isFile = entry?.type === 'blob'
304
303
  if (change.content === undefined && !isFile) throw configurationError()
305
- result.push(isFile && existing.mode === '100755' ? { ...change, mode: '100755' } : change)
306
- }
307
- return result
304
+ return isFile && entry.mode === '100755' ? { ...change, mode: '100755' } : change
305
+ })
308
306
  }
309
307
 
310
- #treeWalker(rootSha: string, signal: AbortSignal | undefined): TreeWalker {
311
- return new TreeWalker(rootSha, (treeSha) => this.#readGitObject(`/git/trees/${treeSha}`, signal, MAX_TREE_RESPONSE_BYTES))
308
+ /** The entry at `path` in `commitSha`, or null. One listing of its directory, which this client reads once. */
309
+ async #find(commitSha: string, path: string, signal: AbortSignal | undefined): Promise<GitHubTreeEntry | null> {
310
+ const slash = path.lastIndexOf('/')
311
+ const listing = await this.#readTreeAt(commitSha, slash === -1 ? '' : path.slice(0, slash), '', signal)
312
+ if (listing?.truncated === true) throw responseError()
313
+ return listing?.entries.find((entry) => entry.path === path.slice(slash + 1)) ?? null
314
+ }
315
+
316
+ /**
317
+ * The tree of `directory` ('' for the root) at `commitSha`, in one request: GitHub resolves `<commit>:<path>`. Null
318
+ * when the commit holds no such directory; an unknown commit is not found.
319
+ */
320
+ async #readTreeAt(commitSha: string, directory: string, query: '' | '?recursive=1', signal: AbortSignal | undefined): Promise<DecodedTree | null> {
321
+ const path = `/git/trees/${encodeURIComponent(`${commitSha}:${directory}`)}${query}`
322
+ let body: unknown
323
+ try {
324
+ body = await this.#readGitObject(path, signal, MAX_TREE_RESPONSE_BYTES)
325
+ } catch (error) {
326
+ if (!(error instanceof GitHubNotFoundError)) throw error
327
+ // GitHub answers the same for a missing directory and an unknown commit; only the commit read tells them apart.
328
+ await this.#readCommit(commitSha, signal)
329
+ return null
330
+ }
331
+ return decodeTreeListing(body)
312
332
  }
313
333
 
314
334
  async #readCommit(sha: string, signal: AbortSignal | undefined): Promise<GitHubCommit> {
@@ -318,7 +338,17 @@ class RepositoryClient implements GitHubRepositoryClient {
318
338
  }
319
339
 
320
340
  /** Reads a commit, tree or blob by sha; GitHub answers 404 or 422 for an unknown one. */
321
- async #readGitObject(path: string, signal: AbortSignal | undefined, maxResponseBytes?: number): Promise<unknown> {
341
+ #readGitObject(path: string, signal: AbortSignal | undefined, maxResponseBytes?: number): Promise<unknown> {
342
+ if (path.startsWith('/git/blobs/')) return this.#fetchGitObject(path, signal, maxResponseBytes)
343
+ const cached = this.#objects.get(path)
344
+ if (cached !== undefined) return cached
345
+ const read = this.#fetchGitObject(path, signal, maxResponseBytes)
346
+ this.#objects.set(path, read)
347
+ read.catch(() => this.#objects.delete(path))
348
+ return read
349
+ }
350
+
351
+ async #fetchGitObject(path: string, signal: AbortSignal | undefined, maxResponseBytes?: number): Promise<unknown> {
322
352
  const result = await this.#request(path, { signal, maxResponseBytes, expectedFailures: [404, 422] })
323
353
  if (!result.ok) throw new GitHubNotFoundError()
324
354
  return result.body
@@ -343,7 +373,8 @@ class RepositoryClient implements GitHubRepositoryClient {
343
373
  method: options.method ?? 'GET',
344
374
  headers,
345
375
  ...(options.body === undefined ? {} : { body: JSON.stringify(options.body) }),
346
- redirect: 'error',
376
+ // Workers refuse `redirect: 'error'`; a redirect is a response that is not `ok` and fails below.
377
+ redirect: 'manual',
347
378
  signal: cancellation.signal,
348
379
  })
349
380
  } catch {
@@ -365,55 +396,6 @@ class RepositoryClient implements GitHubRepositoryClient {
365
396
  }
366
397
 
367
398
  /** Resolves repository paths through non-recursive tree reads, caching each directory once. */
368
- class TreeWalker {
369
- readonly #directories = new Map<string, Promise<ReadonlyMap<string, GitHubTreeEntry>>>()
370
-
371
- constructor(
372
- private readonly rootSha: string,
373
- private readonly fetchTree: (treeSha: string) => Promise<unknown>,
374
- ) {}
375
-
376
- async find(path: string): Promise<GitHubTreeEntry | null> {
377
- let treeSha = this.rootSha
378
- const parts = path.split('/')
379
- for (const [index, part] of parts.entries()) {
380
- const entry = (await this.#read(treeSha)).get(part)
381
- if (entry === undefined) return null
382
- if (index === parts.length - 1) return entry
383
- if (entry.type !== 'tree') return null
384
- treeSha = entry.sha
385
- }
386
- return null
387
- }
388
-
389
- #read(treeSha: string): Promise<ReadonlyMap<string, GitHubTreeEntry>> {
390
- let directory = this.#directories.get(treeSha)
391
- if (directory === undefined) {
392
- directory = this.#load(treeSha)
393
- this.#directories.set(treeSha, directory)
394
- }
395
- return directory
396
- }
397
-
398
- async #load(treeSha: string): Promise<ReadonlyMap<string, GitHubTreeEntry>> {
399
- const tree = decodeTree(await this.fetchTree(treeSha), treeSha)
400
- // A truncated directory listing cannot prove a path is absent.
401
- if (tree.truncated) throw responseError()
402
- return new Map(tree.entries.map((entry) => [entry.path, entry]))
403
- }
404
- }
405
-
406
- type GitHubBlobEntry = Extract<GitHubTreeEntry, { readonly type: 'blob' }>
407
-
408
- /** The entry when it is a regular file within both bounds, otherwise why it is not read. */
409
- function readableBlob(entry: GitHubTreeEntry | null, remainingBytes: number): GitHubBlobEntry | GitHubUnreadableReason {
410
- if (entry === null) return 'missing'
411
- if (entry.type !== 'blob' || entry.mode === '120000') return 'not_a_file'
412
- if (entry.size > MAX_FILE_BYTES) return 'too_large'
413
- if (entry.size > remainingBytes) return 'budget'
414
- return entry
415
- }
416
-
417
399
  function requireBranchAt(ref: GitHubRef, sha: string): GitHubRef {
418
400
  if (ref.sha !== sha) throw new GitHubBranchConflictError()
419
401
  return ref
package/src/transport.ts CHANGED
@@ -2,7 +2,7 @@ import { responseError } from './errors'
2
2
 
3
3
  export const GITHUB_ACCEPT = 'application/vnd.github+json'
4
4
  export const GITHUB_API_VERSION = '2022-11-28'
5
- export const GITHUB_USER_AGENT = 'vozka'
5
+ export const GITHUB_USER_AGENT = 'fabrika'
6
6
  const MAX_RESPONSE_BYTES = 64 * 1024
7
7
 
8
8
  interface RequestCancellation {
@@ -135,6 +135,22 @@ function readChunk(
135
135
  })
136
136
  }
137
137
 
138
+ /** Wait `milliseconds`, or reject as soon as the caller aborts. */
139
+ export function pause(milliseconds: number, signal: AbortSignal | undefined): Promise<void> {
140
+ if (signal?.aborted === true) return Promise.reject(abortError())
141
+ return new Promise((resolve, reject) => {
142
+ const abort = (): void => {
143
+ clearTimeout(timer)
144
+ reject(abortError())
145
+ }
146
+ const timer = setTimeout(() => {
147
+ signal?.removeEventListener('abort', abort)
148
+ resolve()
149
+ }, milliseconds)
150
+ signal?.addEventListener('abort', abort, { once: true })
151
+ })
152
+ }
153
+
138
154
  function abortError(): DOMException {
139
155
  return new DOMException('GitHub App request was aborted', 'AbortError')
140
156
  }
package/src/types.ts CHANGED
@@ -11,6 +11,12 @@ export interface GitHubAppClientConfig {
11
11
  now?: () => number
12
12
  /** Upper bound for each GitHub API request, including its response body. */
13
13
  timeoutMs?: number
14
+ /**
15
+ * Anonymous reads of the App's public page before a rate limit is the answer, 1–4; 1 by default. Raise it only where
16
+ * each read may leave from another address (a Worker on a cloud's shared egress): from one fixed address a spent limit
17
+ * stays spent until it resets.
18
+ */
19
+ publicAppAttempts?: number
14
20
  }
15
21
 
16
22
  export interface GitHubInstallationToken {
@@ -0,0 +1,46 @@
1
+ import type { GitHubRepositoryClient, GitHubRepositoryOpenRequest } from './repository-types';
2
+ import type { GitHubAppClientConfig, GitHubAppIdentity, GitHubAppInstallation, GitHubAppWebhookConfig, GitHubAppWebhookUpdate, GitHubInstallationToken, GitHubRepositoryTokenRequest } from './types';
3
+ /** GitHub App machine identity. Webhook authentication belongs to the receiving service. */
4
+ export declare class GitHubAppClient {
5
+ private readonly appId;
6
+ private readonly privateKey;
7
+ private readonly apiBaseUrl;
8
+ private readonly fetchImplementation;
9
+ private readonly clock;
10
+ private readonly timeoutMs;
11
+ private readonly publicAppAttempts;
12
+ private constructor();
13
+ /** Validate all configuration and import the RSA key before a credential-owning service boots. */
14
+ static create(config: GitHubAppClientConfig): Promise<GitHubAppClient>;
15
+ /** Read and bind the public identity represented by this client's App credentials. */
16
+ getAuthenticatedApp(signal?: AbortSignal): Promise<GitHubAppIdentity>;
17
+ /**
18
+ * The App's public page, read without credentials: GitHub answers it only for a public App. The read is anonymous,
19
+ * so it spends the caller's address's limit. Where the next read may leave from another address (a Worker on a cloud's
20
+ * shared egress), the client is configured to try a rate-limited read again after a short wait.
21
+ */
22
+ private publicApp;
23
+ /** Read the App webhook transport settings without exposing GitHub's masked secret field. */
24
+ getWebhookConfig(signal?: AbortSignal): Promise<GitHubAppWebhookConfig>;
25
+ /** Set the App webhook to JSON over verified TLS and bind GitHub's response to that request. */
26
+ updateWebhookConfig(input: GitHubAppWebhookUpdate): Promise<GitHubAppWebhookConfig>;
27
+ /** Resolve the App installation owned by one organization. A 404 is an expected miss. */
28
+ resolveOrganizationInstallationId(organization: string, signal?: AbortSignal): Promise<number | null>;
29
+ /** Resolve and strictly bind the installation authority owned by one organization. */
30
+ resolveOrganizationInstallation(organization: string, signal?: AbortSignal): Promise<GitHubAppInstallation | null>;
31
+ /** Resolve the App installation for one GitHub repository. A 404 is an expected miss. */
32
+ resolveInstallationId(owner: string, repository: string, signal?: AbortSignal): Promise<number | null>;
33
+ /** Resolve and strictly bind the installation authority that grants one repository. */
34
+ resolveRepositoryInstallation(owner: string, repository: string, signal?: AbortSignal): Promise<GitHubAppInstallation | null>;
35
+ /** Mint a read-only token restricted to one repository in the selected installation. */
36
+ mintRepositoryToken(input: GitHubRepositoryTokenRequest): Promise<GitHubInstallationToken>;
37
+ /**
38
+ * Mint a token restricted to one repository with `contents: write` and `pull_requests: write`,
39
+ * and return a client bound to it. The token never leaves the returned client.
40
+ */
41
+ openRepository(input: GitHubRepositoryOpenRequest): Promise<GitHubRepositoryClient>;
42
+ private mintToken;
43
+ private requestJson;
44
+ private decodeInstallation;
45
+ private now;
46
+ }
@@ -0,0 +1,37 @@
1
+ export declare function configurationError(): Error;
2
+ /** GitHub answered a request with an unexpected status; the message never carries GitHub's response text. */
3
+ export declare class GitHubRequestError extends Error {
4
+ readonly status: number;
5
+ constructor(status: number);
6
+ }
7
+ /**
8
+ * GitHub refused a request for its rate limit: a 429, or a 403 that says the limit is spent (`x-ratelimit-remaining: 0`)
9
+ * or when to come back (`retry-after`, GitHub's secondary limit). An anonymous read spends the caller's address's limit,
10
+ * which every tenant of a cloud's shared egress spends with it.
11
+ */
12
+ export declare class GitHubRateLimitError extends GitHubRequestError {
13
+ readonly anonymous: boolean;
14
+ /** When GitHub admits the next request: `retry-after` when it sends one, else `x-ratelimit-reset`. */
15
+ readonly resetAt: Date | undefined;
16
+ /** GitHub's `retry-after`, in milliseconds; only the secondary limit sends it. */
17
+ readonly retryAfterMs: number | undefined;
18
+ constructor(status: number, anonymous: boolean,
19
+ /** When GitHub admits the next request: `retry-after` when it sends one, else `x-ratelimit-reset`. */
20
+ resetAt: Date | undefined,
21
+ /** GitHub's `retry-after`, in milliseconds; only the secondary limit sends it. */
22
+ retryAfterMs: number | undefined);
23
+ }
24
+ export declare function requestStatusError(status: number, headers?: Headers, anonymous?: boolean, now?: () => number): GitHubRequestError;
25
+ export declare function responseError(): Error;
26
+ /** The branch moved since the caller read it; re-read the head and retry the change on top of it. */
27
+ export declare class GitHubStaleHeadError extends Error {
28
+ constructor();
29
+ }
30
+ /** The branch exists at a different commit than the one it was to be created from. */
31
+ export declare class GitHubBranchConflictError extends Error {
32
+ constructor();
33
+ }
34
+ /** A commit, tree or blob sha the caller named does not exist in the repository. */
35
+ export declare class GitHubNotFoundError extends Error {
36
+ constructor();
37
+ }
@@ -0,0 +1,6 @@
1
+ export { GitHubAppClient } from './client';
2
+ export { GitHubBranchConflictError, GitHubNotFoundError, GitHubRateLimitError, GitHubRequestError, GitHubStaleHeadError } from './errors';
3
+ export { buildGitHubAppManifest, exchangeGitHubAppManifestCode } from './manifest';
4
+ export type { GitHubBlobRead, GitHubBlobRef, GitHubChangedFile, GitHubChangedFileStatus, GitHubCommit, GitHubCommitFilesInput, GitHubComparison, GitHubCreateBranchInput, GitHubFileChange, GitHubFileRead, GitHubOpenPullRequestInput, GitHubPullRequestRef, GitHubRef, GitHubRepositoryClient, GitHubRepositoryOpenRequest, GitHubTextFile, GitHubTreeEntry, GitHubTreeListing, GitHubUnreadablePath, GitHubUnreadableReason, } from './repository-types';
5
+ export { pemToPkcs8 } from './signing';
6
+ export type { CreatedGitHubApp, GitHubAppClientConfig, GitHubAppFetch, GitHubAppIdentity, GitHubAppInstallation, GitHubAppManifestExchangeOptions, GitHubAppManifestInput, GitHubAppWebhookConfig, GitHubAppWebhookUpdate, GitHubInstallationToken, GitHubRepositoryTokenRequest, } from './types';
@@ -0,0 +1,8 @@
1
+ import type { CreatedGitHubApp, GitHubAppManifestExchangeOptions, GitHubAppManifestInput } from './types';
2
+ /**
3
+ * Build the one App manifest used by Fabrika repository source and MCP authoring. The write permissions serve
4
+ * MCP authoring's branches and pull requests (`openRepository`); deploy tokens are minted with Contents read only.
5
+ */
6
+ export declare function buildGitHubAppManifest(input: GitHubAppManifestInput): Readonly<Record<string, unknown>>;
7
+ /** Exchange a bounded one-time GitHub manifest code without exposing response details. */
8
+ export declare function exchangeGitHubAppManifestCode(code: string, options?: GitHubAppManifestExchangeOptions): Promise<CreatedGitHubApp>;
@@ -0,0 +1,146 @@
1
+ export interface GitHubRef {
2
+ readonly branch: string;
3
+ readonly sha: string;
4
+ }
5
+ export interface GitHubCommit {
6
+ readonly sha: string;
7
+ readonly treeSha: string;
8
+ readonly parents: readonly string[];
9
+ }
10
+ export type GitHubTreeEntry = {
11
+ readonly path: string;
12
+ readonly sha: string;
13
+ } & ({
14
+ readonly type: 'tree';
15
+ readonly mode: '040000';
16
+ } | {
17
+ readonly type: 'blob';
18
+ readonly mode: '100644' | '100755' | '120000';
19
+ readonly size: number;
20
+ } | {
21
+ readonly type: 'commit';
22
+ readonly mode: '160000';
23
+ });
24
+ export interface GitHubTreeListing {
25
+ readonly commitSha: string;
26
+ /** Empty for the root; entries use repository-relative paths. */
27
+ readonly directory: string;
28
+ /** Every entry below `directory`, recursively, up to the client's bound. */
29
+ readonly entries: readonly GitHubTreeEntry[];
30
+ /** True when the bound cut the listing short. */
31
+ readonly truncated: boolean;
32
+ }
33
+ export interface GitHubTextFile {
34
+ readonly path: string;
35
+ readonly content: string;
36
+ }
37
+ /**
38
+ * Why a requested path was not read: `missing` (no such path), `not_a_file` (a directory, symlink or submodule),
39
+ * `too_large` (over the per-file bound), `binary` (not UTF-8), `budget` (past the read's total byte bound).
40
+ */
41
+ export type GitHubUnreadableReason = 'missing' | 'not_a_file' | 'too_large' | 'binary' | 'budget';
42
+ export interface GitHubUnreadablePath {
43
+ readonly path: string;
44
+ readonly reason: GitHubUnreadableReason;
45
+ }
46
+ export interface GitHubFileRead {
47
+ readonly commitSha: string;
48
+ readonly files: readonly GitHubTextFile[];
49
+ /** Requested paths that were not read at `commitSha`, in request order. */
50
+ readonly unreadable: readonly GitHubUnreadablePath[];
51
+ }
52
+ /** A blob named by a tree listing of the same repository. */
53
+ export interface GitHubBlobRef {
54
+ readonly path: string;
55
+ readonly sha: string;
56
+ readonly size: number;
57
+ }
58
+ export interface GitHubBlobRead {
59
+ readonly files: readonly GitHubTextFile[];
60
+ /** Blobs that were not read (`too_large`, `budget` or `binary`), in request order. */
61
+ readonly unreadable: readonly GitHubUnreadablePath[];
62
+ }
63
+ export type GitHubChangedFileStatus = 'added' | 'removed' | 'modified' | 'renamed' | 'copied' | 'changed' | 'unchanged';
64
+ export interface GitHubChangedFile {
65
+ readonly path: string;
66
+ /** The path before a rename or copy. */
67
+ readonly previousPath: string | null;
68
+ readonly status: GitHubChangedFileStatus;
69
+ readonly additions: number;
70
+ readonly deletions: number;
71
+ /** The unified diff hunk; null when GitHub omits it (a binary file or a very large change). */
72
+ readonly patch: string | null;
73
+ }
74
+ export interface GitHubComparison {
75
+ readonly baseSha: string;
76
+ readonly headSha: string;
77
+ /** Commits on head that are not on base. */
78
+ readonly aheadBy: number;
79
+ readonly behindBy: number;
80
+ readonly files: readonly GitHubChangedFile[];
81
+ /** GitHub lists at most 300 files of a comparison; true when it listed that many, so more may have changed. */
82
+ readonly filesCapped: boolean;
83
+ }
84
+ export interface GitHubFileChange {
85
+ readonly path: string;
86
+ /** UTF-8 regular-file contents, or null to delete the path. */
87
+ readonly content: string | null;
88
+ }
89
+ export interface GitHubCreateBranchInput {
90
+ readonly branch: string;
91
+ readonly fromSha: string;
92
+ readonly signal?: AbortSignal;
93
+ }
94
+ export interface GitHubCommitFilesInput {
95
+ readonly branch: string;
96
+ /** The branch head the changes were made against; a different live head fails with `GitHubStaleHeadError`. */
97
+ readonly expectedHeadSha: string;
98
+ readonly message: string;
99
+ readonly author: {
100
+ readonly name: string;
101
+ readonly email: string;
102
+ };
103
+ readonly changes: readonly GitHubFileChange[];
104
+ readonly signal?: AbortSignal;
105
+ }
106
+ export interface GitHubOpenPullRequestInput {
107
+ readonly head: string;
108
+ readonly base: string;
109
+ readonly title: string;
110
+ readonly body: string;
111
+ readonly signal?: AbortSignal;
112
+ }
113
+ export interface GitHubPullRequestRef {
114
+ readonly number: number;
115
+ readonly url: string;
116
+ /** False when an open pull request for the same head and base already existed and was returned instead. */
117
+ readonly created: boolean;
118
+ }
119
+ /**
120
+ * One repository, reached with an installation token restricted to it. The caller (Source) decides
121
+ * which branches it may write; the client only refuses a non-fast-forward or stale update.
122
+ */
123
+ export interface GitHubRepositoryClient {
124
+ readRef(branch: string, signal?: AbortSignal): Promise<GitHubRef | null>;
125
+ readTree(commitSha: string, directory?: string, signal?: AbortSignal): Promise<GitHubTreeListing>;
126
+ readFiles(commitSha: string, paths: readonly string[], signal?: AbortSignal): Promise<GitHubFileRead>;
127
+ /** Reads listed blobs as text without walking the tree again, within the same per-file and total bounds as `readFiles`. */
128
+ readBlobTexts(blobs: readonly GitHubBlobRef[], signal?: AbortSignal): Promise<GitHubBlobRead>;
129
+ /** The changes from the merge base of `baseSha` and `headSha` to `headSha`. */
130
+ compareCommits(baseSha: string, headSha: string, signal?: AbortSignal): Promise<GitHubComparison>;
131
+ /** Idempotent: an existing branch already at `fromSha` is returned; one elsewhere is a conflict. */
132
+ createBranch(input: GitHubCreateBranchInput): Promise<GitHubRef>;
133
+ /** Idempotent: `deleted` is false when the branch did not exist. GitHub closes an open pull request from it. */
134
+ deleteBranch(branch: string, signal?: AbortSignal): Promise<{
135
+ readonly deleted: boolean;
136
+ }>;
137
+ /** Creates exactly one commit on top of `expectedHeadSha` and moves the branch to it without force. */
138
+ commitFiles(input: GitHubCommitFilesInput): Promise<GitHubCommit>;
139
+ openPullRequest(input: GitHubOpenPullRequestInput): Promise<GitHubPullRequestRef>;
140
+ }
141
+ export interface GitHubRepositoryOpenRequest {
142
+ readonly installationId: number;
143
+ readonly owner: string;
144
+ readonly repository: string;
145
+ readonly signal?: AbortSignal;
146
+ }
@@ -0,0 +1,40 @@
1
+ import type { GitHubCommit, GitHubComparison, GitHubPullRequestRef, GitHubRef, GitHubTreeEntry } from './repository-types';
2
+ export declare const MAX_TREE_ENTRIES = 5000;
3
+ export declare const MAX_TREE_RESPONSE_BYTES: number;
4
+ export declare const MAX_READ_PATHS = 100;
5
+ export declare const MAX_FILE_BYTES: number;
6
+ export declare const MAX_READ_BYTES: number;
7
+ export declare const MAX_BLOB_RESPONSE_BYTES: number;
8
+ export declare const MAX_CHANGED_FILES = 256;
9
+ export declare const MAX_CHANGED_BYTES: number;
10
+ export declare const MAX_COMMIT_MESSAGE_BYTES: number;
11
+ export declare const MAX_PULL_REQUEST_TITLE_BYTES = 1024;
12
+ export declare const MAX_PULL_REQUEST_BODY_BYTES: number;
13
+ export declare const MAX_PULL_REQUEST_RESPONSE_BYTES: number;
14
+ export declare const MAX_COMMIT_RESPONSE_BYTES: number;
15
+ export declare const MAX_PATH_SEGMENTS = 64;
16
+ /** GitHub's own bound on the files of one comparison. */
17
+ export declare const MAX_COMPARE_FILES = 300;
18
+ export declare const MAX_COMPARE_RESPONSE_BYTES: number;
19
+ export declare function validateSha(value: string): void;
20
+ /** A subset of `git check-ref-format` that is safe to place in a URL path segment by segment. */
21
+ export declare function validateBranch(value: string): void;
22
+ /** Repository-relative path: no leading, trailing or doubled slash, no `.`/`..` segment, never inside `.git`. */
23
+ export declare function validatePath(value: string): void;
24
+ export declare function validateText(value: string, maxBytes: number, allowEmpty: boolean): void;
25
+ export declare function utf8Length(value: string): number;
26
+ export declare function encodeBranch(branch: string): string;
27
+ export declare function decodeRef(body: unknown, branch: string): GitHubRef;
28
+ export declare function decodeCommit(body: unknown): GitHubCommit;
29
+ export interface DecodedTree {
30
+ readonly entries: readonly GitHubTreeEntry[];
31
+ readonly truncated: boolean;
32
+ }
33
+ /** A tree read by `<commit>:<path>`, whose own sha the request did not name. */
34
+ export declare function decodeTreeListing(body: unknown): DecodedTree;
35
+ export declare function decodeCreatedTreeSha(body: unknown): string;
36
+ /** The blob's bytes as UTF-8 text, or null when they are not valid UTF-8. */
37
+ export declare function decodeTextBlob(body: unknown, expectedSha: string, expectedSize: number): string | null;
38
+ export declare function decodeComparison(body: unknown, headSha: string): GitHubComparison;
39
+ export declare function decodePullRequest(body: unknown, created: boolean): GitHubPullRequestRef;
40
+ export declare function decodePullRequestList(body: unknown): unknown[];
@@ -0,0 +1,12 @@
1
+ import type { GitHubRepositoryClient } from './repository-types';
2
+ import type { GitHubAppFetch, GitHubInstallationToken } from './types';
3
+ export interface RepositoryClientConfig {
4
+ readonly owner: string;
5
+ readonly repository: string;
6
+ readonly token: GitHubInstallationToken;
7
+ readonly now: () => number;
8
+ readonly apiBaseUrl: string;
9
+ readonly fetch: GitHubAppFetch;
10
+ readonly timeoutMs: number;
11
+ }
12
+ export declare function createRepositoryClient(config: RepositoryClientConfig): GitHubRepositoryClient;
@@ -0,0 +1,3 @@
1
+ export declare function signAppJwt(appId: string, privateKey: CryptoKey, clock: () => number): Promise<string>;
2
+ /** Convert a GitHub App PKCS1 or PKCS8 PEM key into PKCS8 DER for WebCrypto. */
3
+ export declare function pemToPkcs8(pem: string): Uint8Array<ArrayBuffer>;
@@ -0,0 +1,13 @@
1
+ export declare const GITHUB_ACCEPT = "application/vnd.github+json";
2
+ export declare const GITHUB_API_VERSION = "2022-11-28";
3
+ export declare const GITHUB_USER_AGENT = "fabrika";
4
+ interface RequestCancellation {
5
+ readonly signal: AbortSignal;
6
+ throwIfCancelled(): void;
7
+ dispose(): void;
8
+ }
9
+ export declare function createCancellation(callerSignal: AbortSignal | undefined, timeoutMs: number): RequestCancellation;
10
+ export declare function readBoundedJson(response: Response, cancellation: RequestCancellation, maxResponseBytes?: number): Promise<unknown>;
11
+ /** Wait `milliseconds`, or reject as soon as the caller aborts. */
12
+ export declare function pause(milliseconds: number, signal: AbortSignal | undefined): Promise<void>;
13
+ export {};
@@ -0,0 +1,85 @@
1
+ export interface GitHubAppClientConfig {
2
+ /** Numeric GitHub App id, kept as a string because it is the JWT issuer. */
3
+ appId: string;
4
+ /** GitHub App RSA private key in PKCS1 or PKCS8 PEM form. */
5
+ privateKeyPem: string;
6
+ /** GitHub API base URL. Defaults to the public GitHub API. */
7
+ apiBaseUrl?: string;
8
+ /** HTTP implementation for the current runtime. */
9
+ fetch?: GitHubAppFetch;
10
+ /** Millisecond Unix clock. */
11
+ now?: () => number;
12
+ /** Upper bound for each GitHub API request, including its response body. */
13
+ timeoutMs?: number;
14
+ /**
15
+ * Anonymous reads of the App's public page before a rate limit is the answer, 1–4; 1 by default. Raise it only where
16
+ * each read may leave from another address (a Worker on a cloud's shared egress): from one fixed address a spent limit
17
+ * stays spent until it resets.
18
+ */
19
+ publicAppAttempts?: number;
20
+ }
21
+ export interface GitHubInstallationToken {
22
+ token: string;
23
+ expiresAt: number;
24
+ }
25
+ export interface GitHubAppInstallation {
26
+ readonly id: number;
27
+ readonly accountLogin: string;
28
+ readonly accountType: 'Organization' | 'User';
29
+ readonly repositorySelection: 'all' | 'selected';
30
+ }
31
+ export interface GitHubAppIdentity {
32
+ readonly id: number;
33
+ readonly slug: string;
34
+ readonly htmlUrl: string;
35
+ readonly public: boolean;
36
+ readonly permissions: {
37
+ readonly contents: 'read' | 'write';
38
+ readonly pull_requests?: 'read' | 'write';
39
+ };
40
+ readonly events: readonly string[];
41
+ readonly owner: {
42
+ readonly login: string;
43
+ readonly type: 'Organization' | 'User';
44
+ };
45
+ }
46
+ export interface GitHubAppWebhookConfig {
47
+ readonly url: string;
48
+ readonly contentType: 'json' | 'form';
49
+ readonly insecureSsl: '0' | '1';
50
+ }
51
+ export interface GitHubAppWebhookUpdate {
52
+ readonly url: string;
53
+ readonly secret: string;
54
+ readonly signal?: AbortSignal;
55
+ }
56
+ export interface GitHubRepositoryTokenRequest {
57
+ installationId: number;
58
+ owner: string;
59
+ repository: string;
60
+ signal?: AbortSignal;
61
+ }
62
+ export type GitHubAppFetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
63
+ export interface CreatedGitHubApp {
64
+ readonly id: number;
65
+ readonly slug: string;
66
+ readonly htmlUrl: string;
67
+ readonly pem: string;
68
+ readonly webhookSecret: string;
69
+ }
70
+ export interface GitHubAppManifestInput {
71
+ readonly organization: string;
72
+ readonly appName: string;
73
+ readonly homepageUrl: string;
74
+ readonly webhookUrl: string;
75
+ readonly redirectUrl?: string;
76
+ /** Where GitHub sends the installer after an install or an installation update, with `installation_id` and `setup_action`. */
77
+ readonly setupUrl?: string;
78
+ /** GitHub requires a public App when repositories outside its owner organization need it. */
79
+ readonly public: boolean;
80
+ }
81
+ export interface GitHubAppManifestExchangeOptions {
82
+ readonly fetch?: GitHubAppFetch;
83
+ readonly signal?: AbortSignal;
84
+ readonly timeoutMs?: number;
85
+ }
@@ -0,0 +1,69 @@
1
+ import { z } from 'zod';
2
+ import type { GitHubAppIdentity, GitHubAppWebhookConfig } from './types';
3
+ export declare const APP_SLUG_PATTERN: RegExp;
4
+ export declare const appReferenceSchema: z.ZodObject<{
5
+ id: z.ZodNumber;
6
+ slug: z.ZodString;
7
+ html_url: z.ZodString;
8
+ }, "strip", z.ZodTypeAny, {
9
+ id: number;
10
+ slug: string;
11
+ html_url: string;
12
+ }, {
13
+ id: number;
14
+ slug: string;
15
+ html_url: string;
16
+ }>;
17
+ export declare const installationSchema: z.ZodObject<{
18
+ id: z.ZodNumber;
19
+ app_id: z.ZodNumber;
20
+ target_type: z.ZodEnum<["Organization", "User"]>;
21
+ account: z.ZodObject<{
22
+ login: z.ZodString;
23
+ type: z.ZodEnum<["Organization", "User"]>;
24
+ }, "strip", z.ZodTypeAny, {
25
+ type: "Organization" | "User";
26
+ login: string;
27
+ }, {
28
+ type: "Organization" | "User";
29
+ login: string;
30
+ }>;
31
+ repository_selection: z.ZodEnum<["all", "selected"]>;
32
+ }, "strip", z.ZodTypeAny, {
33
+ id: number;
34
+ app_id: number;
35
+ target_type: "Organization" | "User";
36
+ account: {
37
+ type: "Organization" | "User";
38
+ login: string;
39
+ };
40
+ repository_selection: "all" | "selected";
41
+ }, {
42
+ id: number;
43
+ app_id: number;
44
+ target_type: "Organization" | "User";
45
+ account: {
46
+ type: "Organization" | "User";
47
+ login: string;
48
+ };
49
+ repository_selection: "all" | "selected";
50
+ }>;
51
+ export declare const installationTokenSchema: z.ZodObject<{
52
+ token: z.ZodEffects<z.ZodString, string, string>;
53
+ expires_at: z.ZodEffects<z.ZodString, number, string>;
54
+ }, "strip", z.ZodTypeAny, {
55
+ token: string;
56
+ expires_at: number;
57
+ }, {
58
+ token: string;
59
+ expires_at: string;
60
+ }>;
61
+ export declare function normalizeApiBaseUrl(value: string): string;
62
+ export declare function validateRepositoryComponent(value: string): void;
63
+ export declare function normalizeWebhookUrl(value: string): string;
64
+ export declare function validateWebhookSecret(value: string): void;
65
+ export declare function decodeAppIdentity(value: unknown): Omit<GitHubAppIdentity, 'public'> | null;
66
+ export declare function sameAppIdentity(left: Omit<GitHubAppIdentity, 'public'>, right: Omit<GitHubAppIdentity, 'public'>): boolean;
67
+ export declare function decodeWebhookConfig(value: unknown): GitHubAppWebhookConfig | null;
68
+ export declare function hasAsciiControl(value: string): boolean;
69
+ export declare function isPositiveSafeInteger(value: number): boolean;