@nera-static/mcp 1.3.0 → 1.4.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/.claude-plugin/plugin.json +2 -2
- package/CHANGELOG.md +28 -0
- package/README.md +58 -1
- package/bin/nera-mcp.js +203 -61
- package/docs/llms-full.txt +1122 -153
- package/package.json +3 -1
- package/src/hosted/app.js +129 -0
- package/src/hosted/checkout.js +427 -0
- package/src/hosted/config.js +89 -0
- package/src/hosted/consent.js +141 -0
- package/src/hosted/crypto.js +90 -0
- package/src/hosted/github.js +157 -0
- package/src/hosted/mcp.js +62 -0
- package/src/hosted/provider.js +369 -0
- package/src/hosted/repo.js +475 -0
- package/src/hosted/store.js +472 -0
- package/src/hosted/tools/publish.js +166 -0
- package/src/hosted/tools/read.js +336 -0
- package/src/hosted/tools/validate.js +44 -0
- package/src/hosted/tools/write.js +182 -0
- package/src/pages.js +168 -0
- package/src/prompts.js +52 -0
- package/src/resources.js +15 -3
- package/src/runner.js +17 -9
- package/src/tools/cli.js +7 -1
- package/src/tools/files.js +5 -104
- package/src/tools/long-running.js +2 -2
- package/src/tools/sites.js +31 -7
|
@@ -0,0 +1,475 @@
|
|
|
1
|
+
// The GitHub repository side of the hosted mode (L7b, plan D2–D6): the user's
|
|
2
|
+
// repository is the working copy. This client reads files and trees, keeps the
|
|
3
|
+
// draft branch `nera-draft` (every write commits there, so nothing deploys),
|
|
4
|
+
// commits one file change at a time through the Git Data API, merges the
|
|
5
|
+
// draft into `main` (one push, so one deploy), downloads a tarball for
|
|
6
|
+
// `validate` and reads the deploy workflow's runs and the GitHub Pages
|
|
7
|
+
// address for `publish` and `preview`. It is GitHub plumbing, not Nera logic;
|
|
8
|
+
// the page rules live in src/pages.js. Every call goes through the injected
|
|
9
|
+
// `fetch`, so tests never touch the network, and no message it builds can
|
|
10
|
+
// carry the token.
|
|
11
|
+
import { ToolError } from '../results.js'
|
|
12
|
+
import { GitHubError } from './github.js'
|
|
13
|
+
|
|
14
|
+
const USER_AGENT = 'nera-mcp'
|
|
15
|
+
const API_VERSION = '2022-11-28'
|
|
16
|
+
/** The branch a site deploys from. */
|
|
17
|
+
export const BASE_BRANCH = 'main'
|
|
18
|
+
/** The branch every write commits to until `publish` merges it (plan D2). */
|
|
19
|
+
export const DRAFT_BRANCH = 'nera-draft'
|
|
20
|
+
/** GitHub's largest page size; more than this many pages of repositories is not followed. */
|
|
21
|
+
const PER_PAGE = 100
|
|
22
|
+
const MAX_PAGES = 10
|
|
23
|
+
/** The default cap on a downloaded tarball. */
|
|
24
|
+
const MAX_TARBALL_BYTES = 50 * 1024 * 1024
|
|
25
|
+
/** git's modes of a regular and of an executable file. */
|
|
26
|
+
const FILE_MODE = '100644'
|
|
27
|
+
const EXECUTABLE_MODE = '100755'
|
|
28
|
+
/** `owner/name` as GitHub allows them: no slashes, dots or spaces where they could leave the API path. */
|
|
29
|
+
const REPO_NAME = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]{1,100}$/
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Reads a response body of at most `maxBytes`: a larger `content-length` is
|
|
33
|
+
* refused before reading, a body that grows past the cap while it streams is
|
|
34
|
+
* refused the moment it does.
|
|
35
|
+
*
|
|
36
|
+
* @param {Response} response
|
|
37
|
+
* @param {number} maxBytes
|
|
38
|
+
* @param {() => Error} tooLarge the error to throw
|
|
39
|
+
* @returns {Promise<Buffer>}
|
|
40
|
+
*/
|
|
41
|
+
export async function readLimited(response, maxBytes, tooLarge) {
|
|
42
|
+
if (Number(response.headers.get('content-length')) > maxBytes) {
|
|
43
|
+
await response.body?.cancel()
|
|
44
|
+
throw tooLarge()
|
|
45
|
+
}
|
|
46
|
+
const chunks = []
|
|
47
|
+
let size = 0
|
|
48
|
+
for await (const chunk of response.body ?? []) {
|
|
49
|
+
size += chunk.length
|
|
50
|
+
if (size > maxBytes) throw tooLarge()
|
|
51
|
+
chunks.push(chunk)
|
|
52
|
+
}
|
|
53
|
+
return Buffer.concat(chunks)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Checks a repository path a model passed: relative, POSIX, no `..`, `.` or
|
|
58
|
+
* empty segments, no backslashes. There is no filesystem to `realpath`
|
|
59
|
+
* against, so the path itself is all there is to check.
|
|
60
|
+
*
|
|
61
|
+
* @param {string} input e.g. `pages/about.md`
|
|
62
|
+
* @param {string} [label] how the message names the argument
|
|
63
|
+
* @returns {string} the same path, safe to put into an API URL and a tree entry
|
|
64
|
+
* @throws {ToolError}
|
|
65
|
+
*/
|
|
66
|
+
export function repoPath(input, label = 'path') {
|
|
67
|
+
if (typeof input !== 'string' || input === '') {
|
|
68
|
+
throw new ToolError(`The ${label} is empty. Give a path relative to the repository root, e.g. pages/about.md.`)
|
|
69
|
+
}
|
|
70
|
+
if (input.includes('\\')) {
|
|
71
|
+
throw new ToolError(`The ${label} "${input}" contains a backslash. Use forward slashes, e.g. pages/blog/post.md.`)
|
|
72
|
+
}
|
|
73
|
+
if (input.startsWith('/')) {
|
|
74
|
+
throw new ToolError(`The ${label} "${input}" is absolute. Give it relative to the repository root, e.g. ${input.replace(/^\/+/, '') || 'pages/about.md'}.`)
|
|
75
|
+
}
|
|
76
|
+
const segments = input.split('/')
|
|
77
|
+
if (segments.some((segment) => segment === '')) {
|
|
78
|
+
throw new ToolError(`The ${label} "${input}" has an empty segment (a doubled or trailing /). Give it like pages/blog/post.md.`)
|
|
79
|
+
}
|
|
80
|
+
if (segments.some((segment) => segment === '..' || segment === '.')) {
|
|
81
|
+
throw new ToolError(`The ${label} "${input}" contains "." or ".." segments. Give the path inside the repository directly, e.g. pages/about.md.`)
|
|
82
|
+
}
|
|
83
|
+
if (/[\0-\x1f]/.test(input)) {
|
|
84
|
+
throw new ToolError(`The ${label} "${input}" contains a control character.`)
|
|
85
|
+
}
|
|
86
|
+
return input
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Checks a site name: a GitHub repository as `owner/name`.
|
|
91
|
+
*
|
|
92
|
+
* @param {string} site
|
|
93
|
+
* @returns {string}
|
|
94
|
+
* @throws {ToolError}
|
|
95
|
+
*/
|
|
96
|
+
export function repoName(site) {
|
|
97
|
+
if (typeof site !== 'string' || !REPO_NAME.test(site) || site.split('/')[1].startsWith('.')) {
|
|
98
|
+
throw new ToolError(`"${site}" is not a GitHub repository name. Give the site as owner/name, e.g. octo/my-site — list_sites lists the ones you can edit.`)
|
|
99
|
+
}
|
|
100
|
+
return site
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Checks a commit message a model passed: not empty.
|
|
105
|
+
*
|
|
106
|
+
* @param {string} message
|
|
107
|
+
* @returns {string}
|
|
108
|
+
* @throws {ToolError}
|
|
109
|
+
*/
|
|
110
|
+
export function commitMessage(message) {
|
|
111
|
+
if (typeof message !== 'string' || message.trim() === '') {
|
|
112
|
+
throw new ToolError('The commit message is empty. Say in one line what the change does, e.g. "Add the about page".')
|
|
113
|
+
}
|
|
114
|
+
return message
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** `path` with each segment percent-encoded, for an API URL. */
|
|
118
|
+
function encodePath(path) {
|
|
119
|
+
return path.split('/').map(encodeURIComponent).join('/')
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Creates a client for the repositories of one signed-in user.
|
|
124
|
+
*
|
|
125
|
+
* @param {object} options
|
|
126
|
+
* @param {string} options.token the user's GitHub token (from `provider.githubToken`)
|
|
127
|
+
* @param {typeof fetch} [options.fetch]
|
|
128
|
+
* @param {string} [options.apiUrl] `https://api.github.com`, overridable for tests
|
|
129
|
+
*/
|
|
130
|
+
export function createRepoClient({ token, fetch = globalThis.fetch, apiUrl = 'https://api.github.com' }) {
|
|
131
|
+
if (!token) throw new Error('The repository client needs the user\'s GitHub token.')
|
|
132
|
+
|
|
133
|
+
/** Removes the token from a text that came from elsewhere (an error of `fetch`). */
|
|
134
|
+
const redact = (text) => String(text).split(token).join('[token]')
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Calls the REST API.
|
|
138
|
+
*
|
|
139
|
+
* @param {string} method
|
|
140
|
+
* @param {string} pathname from the API root, already encoded
|
|
141
|
+
* @param {object} [options]
|
|
142
|
+
* @param {object} [options.body] sent as JSON
|
|
143
|
+
* @param {number[]} [options.accept] statuses besides 2xx the caller handles itself
|
|
144
|
+
* @param {boolean} [options.raw] leave the answer's body unread (a download)
|
|
145
|
+
* @returns {Promise<{status: number, body: any, response: Response}>}
|
|
146
|
+
*/
|
|
147
|
+
async function request(method, pathname, { body, accept = [], raw = false } = {}) {
|
|
148
|
+
let response
|
|
149
|
+
try {
|
|
150
|
+
response = await fetch(new URL(pathname, apiUrl), {
|
|
151
|
+
method,
|
|
152
|
+
headers: {
|
|
153
|
+
Accept: 'application/vnd.github+json',
|
|
154
|
+
Authorization: `Bearer ${token}`,
|
|
155
|
+
'User-Agent': USER_AGENT,
|
|
156
|
+
'X-GitHub-Api-Version': API_VERSION,
|
|
157
|
+
...(body ? { 'Content-Type': 'application/json' } : {}),
|
|
158
|
+
},
|
|
159
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
160
|
+
})
|
|
161
|
+
} catch (error) {
|
|
162
|
+
throw new GitHubError(`Cannot reach GitHub: ${redact(error.message)}`)
|
|
163
|
+
}
|
|
164
|
+
if (raw && response.ok) return { status: response.status, body: null, response }
|
|
165
|
+
if (response.ok || accept.includes(response.status)) {
|
|
166
|
+
const parsed = response.status === 204 ? null : await response.json().catch(() => null)
|
|
167
|
+
return { status: response.status, body: parsed, response }
|
|
168
|
+
}
|
|
169
|
+
const failed = await response.json().catch(() => ({}))
|
|
170
|
+
const reason = failed?.message ? redact(failed.message) : `HTTP ${response.status}`
|
|
171
|
+
throw new GitHubError(`GitHub refused ${method} ${pathname.split('?')[0]}: ${reason}`, { status: response.status })
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** All pages of a paginated listing, `key` being the array in each answer. */
|
|
175
|
+
async function paginate(pathname, key) {
|
|
176
|
+
const items = []
|
|
177
|
+
for (let page = 1; page <= MAX_PAGES; page += 1) {
|
|
178
|
+
const { body } = await request('GET', `${pathname}?per_page=${PER_PAGE}&page=${page}`)
|
|
179
|
+
const batch = body?.[key] ?? []
|
|
180
|
+
items.push(...batch)
|
|
181
|
+
if (batch.length < PER_PAGE || items.length >= (body?.total_count ?? Infinity)) break
|
|
182
|
+
}
|
|
183
|
+
return items
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const repoUrl = (repo) => `/repos/${repoName(repo)}`
|
|
187
|
+
|
|
188
|
+
/** The commit a branch points at, null when the branch does not exist. */
|
|
189
|
+
async function branchHead(repo, branch) {
|
|
190
|
+
const { status, body } = await request('GET', `${repoUrl(repo)}/git/ref/heads/${encodePath(branch)}`, { accept: [404] })
|
|
191
|
+
return status === 404 ? null : body.object.sha
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Points `branch` at `sha` without force; false when GitHub refuses (422: not a fast-forward). */
|
|
195
|
+
async function moveBranch(repo, branch, sha) {
|
|
196
|
+
const { status } = await request('PATCH', `${repoUrl(repo)}/git/refs/heads/${encodePath(branch)}`, { body: { sha, force: false }, accept: [422] })
|
|
197
|
+
return status !== 422
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Deletes the draft branch; nothing happens when it is already gone. */
|
|
201
|
+
async function deleteDraft(repo) {
|
|
202
|
+
await request('DELETE', `${repoUrl(repo)}/git/refs/heads/${encodePath(DRAFT_BRANCH)}`, { accept: [404, 422] })
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* The mode a file written at `path` on `head` gets: an executable file
|
|
207
|
+
* stays executable (`100755`), anything else — a new file, a regular one —
|
|
208
|
+
* is a regular file (`100644`). A tree too large for one listing
|
|
209
|
+
* (`truncated`, far beyond any site) yields `100644` for files it misses.
|
|
210
|
+
*/
|
|
211
|
+
async function fileMode(repo, head, path) {
|
|
212
|
+
const { body } = await request('GET', `${repoUrl(repo)}/git/trees/${head}?recursive=1`)
|
|
213
|
+
const existing = body.tree.find((candidate) => candidate.path === path && candidate.type === 'blob')
|
|
214
|
+
return existing?.mode === EXECUTABLE_MODE ? EXECUTABLE_MODE : FILE_MODE
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** A commit on `head` that changes the one file `file` to `blob` (null: deleted). */
|
|
218
|
+
async function commitOn(repo, head, file, blob, message) {
|
|
219
|
+
const entry = blob === null
|
|
220
|
+
? { path: file, mode: FILE_MODE, type: 'blob', sha: null }
|
|
221
|
+
: { path: file, mode: await fileMode(repo, head, file), type: 'blob', sha: blob }
|
|
222
|
+
const { body: parent } = await request('GET', `${repoUrl(repo)}/git/commits/${head}`)
|
|
223
|
+
const { body: tree } = await request('POST', `${repoUrl(repo)}/git/trees`, {
|
|
224
|
+
body: { base_tree: parent.tree.sha, tree: [entry] },
|
|
225
|
+
})
|
|
226
|
+
const { body: commit } = await request('POST', `${repoUrl(repo)}/git/commits`, {
|
|
227
|
+
body: { message, tree: tree.sha, parents: [head] },
|
|
228
|
+
})
|
|
229
|
+
return commit.sha
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
return {
|
|
233
|
+
/**
|
|
234
|
+
* The repositories the GitHub App can reach with the user's token,
|
|
235
|
+
* across all its installations, each once.
|
|
236
|
+
*
|
|
237
|
+
* @returns {Promise<Array<{site: string, owner: string, name: string, defaultBranch: string, private: boolean}>>}
|
|
238
|
+
*/
|
|
239
|
+
async listRepos() {
|
|
240
|
+
const installations = await paginate('/user/installations', 'installations')
|
|
241
|
+
const repos = new Map()
|
|
242
|
+
for (const installation of installations) {
|
|
243
|
+
for (const repo of await paginate(`/user/installations/${encodeURIComponent(installation.id)}/repositories`, 'repositories')) {
|
|
244
|
+
repos.set(repo.full_name, {
|
|
245
|
+
site: repo.full_name,
|
|
246
|
+
owner: repo.owner?.login ?? repo.full_name.split('/')[0],
|
|
247
|
+
name: repo.name,
|
|
248
|
+
defaultBranch: repo.default_branch,
|
|
249
|
+
private: Boolean(repo.private),
|
|
250
|
+
})
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return [...repos.values()].sort((a, b) => a.site.localeCompare(b.site))
|
|
254
|
+
},
|
|
255
|
+
|
|
256
|
+
branchHead,
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Reads one file at a ref.
|
|
260
|
+
*
|
|
261
|
+
* @param {string} repo `owner/name`
|
|
262
|
+
* @param {string} path checked with `repoPath`
|
|
263
|
+
* @param {string} ref a branch or commit
|
|
264
|
+
* @param {object} [options]
|
|
265
|
+
* @param {number} [options.maxBytes] a larger file comes with `content` null, without downloading it
|
|
266
|
+
* @returns {Promise<{type: 'file', content: Buffer|null, size: number, sha: string} | {type: 'dir'} | {type: 'symlink'} | null>} null when nothing is at `path`
|
|
267
|
+
*/
|
|
268
|
+
async readFile(repo, path, ref, { maxBytes = Infinity } = {}) {
|
|
269
|
+
const { status, body } = await request('GET', `${repoUrl(repo)}/contents/${encodePath(repoPath(path))}?ref=${encodeURIComponent(ref)}`, { accept: [404] })
|
|
270
|
+
if (status === 404) return null
|
|
271
|
+
if (Array.isArray(body) || body.type === 'dir') return { type: 'dir' }
|
|
272
|
+
// The contents API follows a symbolic link to a file and answers
|
|
273
|
+
// with the target (another path), so a link is never read through.
|
|
274
|
+
if (body.type === 'symlink' || (body.type === 'file' && body.path !== path)) return { type: 'symlink' }
|
|
275
|
+
if (body.type !== 'file') return null
|
|
276
|
+
if (body.size > maxBytes) return { type: 'file', content: null, size: body.size, sha: body.sha }
|
|
277
|
+
let base64 = body.content
|
|
278
|
+
// Files over 1 MB come without content; the blob API has it.
|
|
279
|
+
if (body.encoding !== 'base64') {
|
|
280
|
+
const { body: blob } = await request('GET', `${repoUrl(repo)}/git/blobs/${body.sha}`)
|
|
281
|
+
base64 = blob.content
|
|
282
|
+
}
|
|
283
|
+
return { type: 'file', content: Buffer.from(base64 ?? '', 'base64'), size: body.size, sha: body.sha }
|
|
284
|
+
},
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* Lists every file and folder at a ref.
|
|
288
|
+
*
|
|
289
|
+
* @param {string} repo `owner/name`
|
|
290
|
+
* @param {string} ref a branch or commit
|
|
291
|
+
* @returns {Promise<{entries: Array<{path: string, type: 'blob'|'tree', mode: string, size?: number}>, truncated: boolean}>}
|
|
292
|
+
* `mode` is git's: `120000` marks a symbolic link
|
|
293
|
+
*/
|
|
294
|
+
async readTree(repo, ref) {
|
|
295
|
+
const { body } = await request('GET', `${repoUrl(repo)}/git/trees/${encodeURIComponent(ref)}?recursive=1`)
|
|
296
|
+
return {
|
|
297
|
+
entries: body.tree
|
|
298
|
+
.filter((entry) => entry.type === 'blob' || entry.type === 'tree')
|
|
299
|
+
.map((entry) => ({ path: entry.path, type: entry.type, mode: entry.mode, ...(entry.size === undefined ? {} : { size: entry.size }) })),
|
|
300
|
+
truncated: Boolean(body.truncated),
|
|
301
|
+
}
|
|
302
|
+
},
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* How many commits `head` has that `base` lacks.
|
|
306
|
+
*
|
|
307
|
+
* @param {string} repo `owner/name`
|
|
308
|
+
* @param {string} base a branch or commit
|
|
309
|
+
* @param {string} head a branch or commit
|
|
310
|
+
* @returns {Promise<number>}
|
|
311
|
+
*/
|
|
312
|
+
async aheadBy(repo, base, head) {
|
|
313
|
+
const { body } = await request('GET', `${repoUrl(repo)}/compare/${encodeURIComponent(base)}...${encodeURIComponent(head)}?per_page=1`)
|
|
314
|
+
return body.ahead_by
|
|
315
|
+
},
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Makes sure the draft branch exists, creating it from `main`.
|
|
319
|
+
*
|
|
320
|
+
* @param {string} repo `owner/name`
|
|
321
|
+
* @returns {Promise<{sha: string, created: boolean}>} the draft's head
|
|
322
|
+
*/
|
|
323
|
+
async ensureDraft(repo) {
|
|
324
|
+
const existing = await branchHead(repo, DRAFT_BRANCH)
|
|
325
|
+
if (existing) return { sha: existing, created: false }
|
|
326
|
+
const base = await branchHead(repo, BASE_BRANCH)
|
|
327
|
+
if (!base) {
|
|
328
|
+
throw new GitHubError(`The repository ${repo} has no ${BASE_BRANCH} branch to start the draft from.`, { status: 404 })
|
|
329
|
+
}
|
|
330
|
+
const { status } = await request('POST', `${repoUrl(repo)}/git/refs`, {
|
|
331
|
+
body: { ref: `refs/heads/${DRAFT_BRANCH}`, sha: base },
|
|
332
|
+
accept: [422],
|
|
333
|
+
})
|
|
334
|
+
// 422: another call created it in the meantime.
|
|
335
|
+
if (status === 422) return { sha: await branchHead(repo, DRAFT_BRANCH), created: false }
|
|
336
|
+
return { sha: base, created: true }
|
|
337
|
+
},
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Commits one file change to the draft branch, which must exist
|
|
341
|
+
* (`ensureDraft`): blob → tree → commit → ref update. When the ref
|
|
342
|
+
* update loses a race (the branch moved), the commit is made once more
|
|
343
|
+
* on the new head; a second lost race is an error. A file that exists
|
|
344
|
+
* keeps its mode (an executable stays executable), a new one is a
|
|
345
|
+
* regular file.
|
|
346
|
+
*
|
|
347
|
+
* @param {string} repo `owner/name`
|
|
348
|
+
* @param {object} change
|
|
349
|
+
* @param {string} change.path checked with `repoPath`
|
|
350
|
+
* @param {string|Buffer|null} change.content the new content; null deletes the file
|
|
351
|
+
* @param {string} change.message the commit message
|
|
352
|
+
* @returns {Promise<{sha: string}>} the new commit
|
|
353
|
+
*/
|
|
354
|
+
async commitFile(repo, { path, content, message }) {
|
|
355
|
+
const file = repoPath(path)
|
|
356
|
+
commitMessage(message)
|
|
357
|
+
let blob = null
|
|
358
|
+
if (content !== null) {
|
|
359
|
+
const { body } = await request('POST', `${repoUrl(repo)}/git/blobs`, {
|
|
360
|
+
body: { content: Buffer.from(content).toString('base64'), encoding: 'base64' },
|
|
361
|
+
})
|
|
362
|
+
blob = body.sha
|
|
363
|
+
}
|
|
364
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
365
|
+
const head = await branchHead(repo, DRAFT_BRANCH)
|
|
366
|
+
if (!head) {
|
|
367
|
+
throw new GitHubError(`The branch ${DRAFT_BRANCH} of ${repo} does not exist.`, { status: 404 })
|
|
368
|
+
}
|
|
369
|
+
const sha = await commitOn(repo, head, file, blob, message)
|
|
370
|
+
if (await moveBranch(repo, DRAFT_BRANCH, sha)) return { sha }
|
|
371
|
+
}
|
|
372
|
+
throw new GitHubError(`The branch ${DRAFT_BRANCH} of ${repo} changed twice while committing ${file}. Try the change again.`, { code: 'conflict', status: 422 })
|
|
373
|
+
},
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* Brings the draft into `main` — a fast-forward when `main` has not
|
|
377
|
+
* moved, else a merge commit; either way one push to `main` — and
|
|
378
|
+
* deletes the draft. `pushed` says whether this call moved `main`.
|
|
379
|
+
* It is false when a racing publish put the draft live first: `main`'s
|
|
380
|
+
* sha read before the merge is already the draft's, or the merge API
|
|
381
|
+
* answers 204 (nothing to merge). A push that did not happen is never
|
|
382
|
+
* reported as one.
|
|
383
|
+
*
|
|
384
|
+
* @param {string} repo `owner/name`
|
|
385
|
+
* @param {string} message the merge commit's message, when one is needed
|
|
386
|
+
* @returns {Promise<{sha: string, fastForward: boolean, pushed: boolean} | null>}
|
|
387
|
+
* `sha` is `main`'s head afterwards; null when there is no draft
|
|
388
|
+
*/
|
|
389
|
+
async mergeDraft(repo, message) {
|
|
390
|
+
const draft = await branchHead(repo, DRAFT_BRANCH)
|
|
391
|
+
if (!draft) return null
|
|
392
|
+
const before = await branchHead(repo, BASE_BRANCH)
|
|
393
|
+
let result
|
|
394
|
+
if (before === draft) {
|
|
395
|
+
result = { sha: draft, fastForward: false, pushed: false }
|
|
396
|
+
} else if (await moveBranch(repo, BASE_BRANCH, draft)) {
|
|
397
|
+
result = { sha: draft, fastForward: true, pushed: true }
|
|
398
|
+
} else {
|
|
399
|
+
const { status, body } = await request('POST', `${repoUrl(repo)}/merges`, {
|
|
400
|
+
body: { base: BASE_BRANCH, head: DRAFT_BRANCH, commit_message: message },
|
|
401
|
+
accept: [409],
|
|
402
|
+
})
|
|
403
|
+
if (status === 409) {
|
|
404
|
+
throw new GitHubError(`The draft of ${repo} conflicts with changes made to ${BASE_BRANCH} in the meantime. Resolve it on GitHub (merge ${DRAFT_BRANCH} into ${BASE_BRANCH}).`, { code: 'merge_conflict', status })
|
|
405
|
+
}
|
|
406
|
+
// 204: main already contains every draft commit, so this call merged nothing.
|
|
407
|
+
result = status === 204
|
|
408
|
+
? { sha: await branchHead(repo, BASE_BRANCH), fastForward: false, pushed: false }
|
|
409
|
+
: { sha: body.sha, fastForward: false, pushed: true }
|
|
410
|
+
}
|
|
411
|
+
await deleteDraft(repo)
|
|
412
|
+
return result
|
|
413
|
+
},
|
|
414
|
+
|
|
415
|
+
deleteDraft,
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* The newest run of a workflow on `main`, null when there is none or
|
|
419
|
+
* the workflow does not exist.
|
|
420
|
+
*
|
|
421
|
+
* @param {string} repo `owner/name`
|
|
422
|
+
* @param {string} workflow the workflow's file name, e.g. `deploy.yml`
|
|
423
|
+
* @param {object} [options]
|
|
424
|
+
* @param {string} [options.sha] only a run of a push of this commit
|
|
425
|
+
* @returns {Promise<{id: number, status: string, conclusion: string|null, url: string, sha: string, event: string, createdAt: string} | null>}
|
|
426
|
+
*/
|
|
427
|
+
async latestRun(repo, workflow, { sha } = {}) {
|
|
428
|
+
const query = new URLSearchParams({ branch: BASE_BRANCH, per_page: '1' })
|
|
429
|
+
if (sha) {
|
|
430
|
+
query.set('head_sha', sha)
|
|
431
|
+
query.set('event', 'push')
|
|
432
|
+
}
|
|
433
|
+
const { status, body } = await request('GET', `${repoUrl(repo)}/actions/workflows/${encodeURIComponent(workflow)}/runs?${query}`, { accept: [404] })
|
|
434
|
+
const run = status === 404 ? null : body?.workflow_runs?.[0]
|
|
435
|
+
// The filters narrow the list; the run is checked again so another commit is never reported as this one.
|
|
436
|
+
if (!run || (sha && run.head_sha !== sha)) return null
|
|
437
|
+
return {
|
|
438
|
+
id: run.id,
|
|
439
|
+
status: run.status,
|
|
440
|
+
conclusion: run.conclusion ?? null,
|
|
441
|
+
url: run.html_url,
|
|
442
|
+
sha: run.head_sha,
|
|
443
|
+
event: run.event,
|
|
444
|
+
createdAt: run.created_at,
|
|
445
|
+
}
|
|
446
|
+
},
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* The address GitHub Pages serves the repository at, null when Pages
|
|
450
|
+
* is not set up for it.
|
|
451
|
+
*
|
|
452
|
+
* @param {string} repo `owner/name`
|
|
453
|
+
* @returns {Promise<string|null>}
|
|
454
|
+
*/
|
|
455
|
+
async pagesUrl(repo) {
|
|
456
|
+
const { status, body } = await request('GET', `${repoUrl(repo)}/pages`, { accept: [404] })
|
|
457
|
+
return status === 404 ? null : (body?.html_url ?? null)
|
|
458
|
+
},
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* Downloads the repository as a gzipped tarball, refusing one larger
|
|
462
|
+
* than `maxBytes`.
|
|
463
|
+
*
|
|
464
|
+
* @param {string} repo `owner/name`
|
|
465
|
+
* @param {string} ref a branch or commit
|
|
466
|
+
* @param {object} [options]
|
|
467
|
+
* @param {number} [options.maxBytes]
|
|
468
|
+
* @returns {Promise<Buffer>}
|
|
469
|
+
*/
|
|
470
|
+
async downloadTarball(repo, ref, { maxBytes = MAX_TARBALL_BYTES } = {}) {
|
|
471
|
+
const { response } = await request('GET', `${repoUrl(repo)}/tarball/${encodeURIComponent(ref)}`, { raw: true })
|
|
472
|
+
return readLimited(response, maxBytes, () => new GitHubError(`The repository ${repo} is larger than the ${maxBytes} bytes a checkout may have.`, { code: 'too_large' }))
|
|
473
|
+
},
|
|
474
|
+
}
|
|
475
|
+
}
|