@nera-static/mcp 1.3.0 → 1.4.1

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