@contentrain/mcp 1.6.0 → 1.8.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/README.md +8 -7
- package/dist/{apply-manager-BJ3nKEls.mjs → apply-manager-BRmB27H5.mjs} +5 -5
- package/dist/{apply-manager-BJ3nKEls.mjs.map → apply-manager-BRmB27H5.mjs.map} +1 -1
- package/dist/branch-lifecycle-7dQoF22r.d.mts +141 -0
- package/dist/branch-lifecycle-7dQoF22r.d.mts.map +1 -0
- package/dist/branch-lifecycle-D7tXOE4f.mjs +444 -0
- package/dist/branch-lifecycle-D7tXOE4f.mjs.map +1 -0
- package/dist/{config-Lw7vpK9n.mjs → config-DlFcTxFG.mjs} +3 -2
- package/dist/config-DlFcTxFG.mjs.map +1 -0
- package/dist/{context-DS40WOdw.mjs → context-CYN__o3Q.mjs} +24 -11
- package/dist/context-CYN__o3Q.mjs.map +1 -0
- package/dist/core/apply-manager.mjs +6 -6
- package/dist/core/config.d.mts.map +1 -1
- package/dist/core/config.mjs +1 -1
- package/dist/core/context.d.mts +20 -2
- package/dist/core/context.d.mts.map +1 -1
- package/dist/core/context.mjs +2 -2
- package/dist/core/doctor.mjs +3 -3
- package/dist/core/validator/index.mjs +2 -2
- package/dist/{detect-DL9mFmaS.mjs → detect-eWS6lvoH.mjs} +1 -1
- package/dist/{detect-DL9mFmaS.mjs.map → detect-eWS6lvoH.mjs.map} +1 -1
- package/dist/{doctor-Dxu_SzZy.mjs → doctor-qiUKCy9b.mjs} +34 -15
- package/dist/doctor-qiUKCy9b.mjs.map +1 -0
- package/dist/git/branch-lifecycle.d.mts +2 -57
- package/dist/git/branch-lifecycle.mjs +3 -3
- package/dist/git/transaction.d.mts +2 -0
- package/dist/git/transaction.d.mts.map +1 -1
- package/dist/git/transaction.mjs +5 -4
- package/dist/{id-CIO9s0x_.mjs → id-DV_T9Ic8.mjs} +1 -1
- package/dist/{id-CIO9s0x_.mjs.map → id-DV_T9Ic8.mjs.map} +1 -1
- package/dist/index.mjs +11 -11
- package/dist/{local-D56D9e5T.mjs → local-BZEUWBoC.mjs} +8 -11
- package/dist/local-BZEUWBoC.mjs.map +1 -0
- package/dist/providers/github/index.d.mts +23 -2
- package/dist/providers/github/index.d.mts.map +1 -1
- package/dist/providers/github/index.mjs +112 -51
- package/dist/providers/github/index.mjs.map +1 -1
- package/dist/providers/gitlab/index.d.mts +3 -1
- package/dist/providers/gitlab/index.d.mts.map +1 -1
- package/dist/providers/gitlab/index.mjs +21 -5
- package/dist/providers/gitlab/index.mjs.map +1 -1
- package/dist/providers/local/index.mjs +6 -5
- package/dist/server/http/index.d.mts +1 -1
- package/dist/server/http/index.mjs +11 -11
- package/dist/{server-WqGx6ait.d.mts → server-DZBcZWhE.d.mts} +1 -1
- package/dist/{server-WqGx6ait.d.mts.map → server-DZBcZWhE.d.mts.map} +1 -1
- package/dist/{server-CufhOunD.mjs → server-tTuinKHD.mjs} +56 -22
- package/dist/server-tTuinKHD.mjs.map +1 -0
- package/dist/server.d.mts +1 -1
- package/dist/server.mjs +11 -11
- package/dist/{transaction-LiTjan9Q.mjs → transaction-qliKvBRL.mjs} +104 -60
- package/dist/transaction-qliKvBRL.mjs.map +1 -0
- package/dist/util/detect.mjs +1 -1
- package/dist/util/id.mjs +1 -1
- package/dist/{validator-Bo06QPVB.mjs → validator-Z3DGNWQ6.mjs} +2 -2
- package/dist/{validator-Bo06QPVB.mjs.map → validator-Z3DGNWQ6.mjs.map} +1 -1
- package/package.json +2 -2
- package/dist/branch-lifecycle-DjX3MXNG.mjs +0 -149
- package/dist/branch-lifecycle-DjX3MXNG.mjs.map +0 -1
- package/dist/config-Lw7vpK9n.mjs.map +0 -1
- package/dist/context-DS40WOdw.mjs.map +0 -1
- package/dist/doctor-Dxu_SzZy.mjs.map +0 -1
- package/dist/git/branch-lifecycle.d.mts.map +0 -1
- package/dist/local-D56D9e5T.mjs.map +0 -1
- package/dist/server-CufhOunD.mjs.map +0 -1
- package/dist/transaction-LiTjan9Q.mjs.map +0 -1
|
@@ -95,8 +95,12 @@ const GITHUB_CAPABILITIES = {
|
|
|
95
95
|
* branch, or the HEAD of `input.base` (or the repo's default branch)
|
|
96
96
|
* when the target branch does not yet exist.
|
|
97
97
|
* 2. Read the base tree SHA from that commit.
|
|
98
|
-
* 3.
|
|
99
|
-
*
|
|
98
|
+
* 3. Map `input.changes` to tree entries — `content` inline for each write,
|
|
99
|
+
* `sha: null` for each deletion. No per-file blob round trip: GitHub
|
|
100
|
+
* creates the blobs as part of `createTree`, which keeps the write to a
|
|
101
|
+
* fixed 3 mutations (tree + commit + ref) regardless of file count and
|
|
102
|
+
* stays under the mutation-rate secondary limit. Mirrors the GitLab
|
|
103
|
+
* provider, which already inlines content in its commit actions.
|
|
100
104
|
* 4. Create a new tree layered on top of the base tree with the collected
|
|
101
105
|
* entries.
|
|
102
106
|
* 5. Create the commit (tree, parents, author).
|
|
@@ -113,7 +117,7 @@ async function applyPlanToGitHub(client, repo, input) {
|
|
|
113
117
|
repo: repo.name,
|
|
114
118
|
commit_sha: baseSha
|
|
115
119
|
})).data.tree.sha;
|
|
116
|
-
const treeEntries =
|
|
120
|
+
const treeEntries = input.changes.map((change) => buildTreeEntry(repo, change));
|
|
117
121
|
const tree = await client.rest.git.createTree({
|
|
118
122
|
owner: repo.owner,
|
|
119
123
|
repo: repo.name,
|
|
@@ -155,7 +159,7 @@ async function applyPlanToGitHub(client, repo, input) {
|
|
|
155
159
|
timestamp: commit.data.author?.date ?? timestamp
|
|
156
160
|
};
|
|
157
161
|
}
|
|
158
|
-
|
|
162
|
+
function buildTreeEntry(repo, change) {
|
|
159
163
|
const path = resolveRepoPath(repo.contentRoot, change.path);
|
|
160
164
|
if (change.content === null) return {
|
|
161
165
|
path,
|
|
@@ -167,12 +171,7 @@ async function buildTreeEntry(client, repo, change) {
|
|
|
167
171
|
path,
|
|
168
172
|
mode: "100644",
|
|
169
173
|
type: "blob",
|
|
170
|
-
|
|
171
|
-
owner: repo.owner,
|
|
172
|
-
repo: repo.name,
|
|
173
|
-
content: change.content,
|
|
174
|
-
encoding: "utf-8"
|
|
175
|
-
})).data.sha
|
|
174
|
+
content: change.content
|
|
176
175
|
};
|
|
177
176
|
}
|
|
178
177
|
async function resolveBaseSha(client, repo, branch, base) {
|
|
@@ -264,27 +263,57 @@ async function getBranchDiff(client, repo, branch, base) {
|
|
|
264
263
|
after: null
|
|
265
264
|
}));
|
|
266
265
|
}
|
|
267
|
-
async function mergeBranch(client, repo, branch, into) {
|
|
266
|
+
async function mergeBranch(client, repo, branch, into, opts) {
|
|
268
267
|
try {
|
|
268
|
+
const response = await client.rest.repos.merge({
|
|
269
|
+
owner: repo.owner,
|
|
270
|
+
repo: repo.name,
|
|
271
|
+
base: into,
|
|
272
|
+
head: branch
|
|
273
|
+
});
|
|
274
|
+
const remote = await cleanupSourceBranch(client, repo, branch, opts);
|
|
269
275
|
return {
|
|
270
276
|
merged: true,
|
|
271
|
-
sha:
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
base: into,
|
|
275
|
-
head: branch
|
|
276
|
-
})).data.sha,
|
|
277
|
-
pullRequestUrl: null
|
|
277
|
+
sha: response.data.sha,
|
|
278
|
+
pullRequestUrl: null,
|
|
279
|
+
...remote ? { remote } : {}
|
|
278
280
|
};
|
|
279
281
|
} catch (error) {
|
|
280
|
-
if (isNotModified(error))
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
282
|
+
if (isNotModified(error)) {
|
|
283
|
+
const remote = await cleanupSourceBranch(client, repo, branch, opts);
|
|
284
|
+
return {
|
|
285
|
+
merged: true,
|
|
286
|
+
sha: null,
|
|
287
|
+
pullRequestUrl: null,
|
|
288
|
+
...remote ? { remote } : {}
|
|
289
|
+
};
|
|
290
|
+
}
|
|
285
291
|
throw error;
|
|
286
292
|
}
|
|
287
293
|
}
|
|
294
|
+
/**
|
|
295
|
+
* Best-effort post-merge deletion of the source branch so merged cr/*
|
|
296
|
+
* branches don't pile up on the remote. Opt out per call with
|
|
297
|
+
* `removeSourceBranch: false` (e.g. a driver that owns cleanup separately).
|
|
298
|
+
* Never throws — the merge itself already succeeded.
|
|
299
|
+
*/
|
|
300
|
+
async function cleanupSourceBranch(client, repo, branch, opts) {
|
|
301
|
+
if (opts?.removeSourceBranch === false) return void 0;
|
|
302
|
+
try {
|
|
303
|
+
await deleteBranch(client, repo, branch);
|
|
304
|
+
return { deleted: true };
|
|
305
|
+
} catch (error) {
|
|
306
|
+
const status = error.status;
|
|
307
|
+
if (status === 404 || status === 422) return {
|
|
308
|
+
deleted: false,
|
|
309
|
+
skipped: "not-found"
|
|
310
|
+
};
|
|
311
|
+
return {
|
|
312
|
+
deleted: false,
|
|
313
|
+
warning: `Could not delete "${branch}": ${error instanceof Error ? error.message : String(error)}`
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
}
|
|
288
317
|
async function isMerged(client, repo, branch, into) {
|
|
289
318
|
return (await client.rest.repos.compareCommits({
|
|
290
319
|
owner: repo.owner,
|
|
@@ -315,14 +344,42 @@ function isNotModified(error) {
|
|
|
315
344
|
* commit SHA. When omitted, GitHub resolves to the repository's default
|
|
316
345
|
* branch — which is usually wrong for Contentrain flows, so callers
|
|
317
346
|
* should always pass the explicit `contentrain` tracking branch.
|
|
347
|
+
*
|
|
348
|
+
* Pass `{ memoize: true }` to dedupe reads within one operation: a repeated
|
|
349
|
+
* `(path, ref)` returns the in-flight/cached promise instead of a fresh
|
|
350
|
+
* `getContent`. This is OPT-IN and only safe for a SHORT-LIVED, read-only
|
|
351
|
+
* reader — a long-lived reader that outlives a write would serve stale
|
|
352
|
+
* results, so the provider's own reader never enables it. Failed reads are
|
|
353
|
+
* evicted so a transient error is retried, not cached forever.
|
|
318
354
|
*/
|
|
319
355
|
var GitHubReader = class {
|
|
320
|
-
|
|
356
|
+
fileMemo = /* @__PURE__ */ new Map();
|
|
357
|
+
listMemo = /* @__PURE__ */ new Map();
|
|
358
|
+
existsMemo = /* @__PURE__ */ new Map();
|
|
359
|
+
constructor(client, repo, opts) {
|
|
321
360
|
this.client = client;
|
|
322
361
|
this.repo = repo;
|
|
362
|
+
this.opts = opts;
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* Run `fetch` through the given memo when memoization is enabled, keyed by
|
|
366
|
+
* `(ref, repoPath)`. A rejected promise is evicted so the next call retries.
|
|
367
|
+
*/
|
|
368
|
+
memoized(memo, repoPath, ref, fetch) {
|
|
369
|
+
if (!this.opts?.memoize) return fetch();
|
|
370
|
+
const key = `${ref ?? ""}:${repoPath}`;
|
|
371
|
+
const cached = memo.get(key);
|
|
372
|
+
if (cached) return cached;
|
|
373
|
+
const promise = fetch();
|
|
374
|
+
memo.set(key, promise);
|
|
375
|
+
promise.catch(() => memo.delete(key));
|
|
376
|
+
return promise;
|
|
323
377
|
}
|
|
324
378
|
async readFile(path, ref) {
|
|
325
379
|
const repoPath = resolveRepoPath(this.repo.contentRoot, path);
|
|
380
|
+
return this.memoized(this.fileMemo, repoPath, ref, () => this.readFileUncached(path, repoPath, ref));
|
|
381
|
+
}
|
|
382
|
+
async readFileUncached(path, repoPath, ref) {
|
|
326
383
|
const data = (await this.client.rest.repos.getContent({
|
|
327
384
|
owner: this.repo.owner,
|
|
328
385
|
repo: this.repo.name,
|
|
@@ -345,34 +402,38 @@ var GitHubReader = class {
|
|
|
345
402
|
}
|
|
346
403
|
async listDirectory(path, ref) {
|
|
347
404
|
const repoPath = resolveRepoPath(this.repo.contentRoot, path);
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
405
|
+
return this.memoized(this.listMemo, repoPath, ref, async () => {
|
|
406
|
+
try {
|
|
407
|
+
const data = (await this.client.rest.repos.getContent({
|
|
408
|
+
owner: this.repo.owner,
|
|
409
|
+
repo: this.repo.name,
|
|
410
|
+
path: repoPath,
|
|
411
|
+
ref
|
|
412
|
+
})).data;
|
|
413
|
+
if (!Array.isArray(data)) return [];
|
|
414
|
+
return data.map((entry) => entry.name);
|
|
415
|
+
} catch (error) {
|
|
416
|
+
if (isNotFoundError(error)) return [];
|
|
417
|
+
throw error;
|
|
418
|
+
}
|
|
419
|
+
});
|
|
361
420
|
}
|
|
362
421
|
async fileExists(path, ref) {
|
|
363
422
|
const repoPath = resolveRepoPath(this.repo.contentRoot, path);
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
423
|
+
return this.memoized(this.existsMemo, repoPath, ref, async () => {
|
|
424
|
+
try {
|
|
425
|
+
await this.client.rest.repos.getContent({
|
|
426
|
+
owner: this.repo.owner,
|
|
427
|
+
repo: this.repo.name,
|
|
428
|
+
path: repoPath,
|
|
429
|
+
ref
|
|
430
|
+
});
|
|
431
|
+
return true;
|
|
432
|
+
} catch (error) {
|
|
433
|
+
if (isNotFoundError(error)) return false;
|
|
434
|
+
throw error;
|
|
435
|
+
}
|
|
436
|
+
});
|
|
376
437
|
}
|
|
377
438
|
};
|
|
378
439
|
//#endregion
|
|
@@ -420,8 +481,8 @@ var GitHubProvider = class {
|
|
|
420
481
|
const resolved = base ?? "main";
|
|
421
482
|
return getBranchDiff(this.client, this.repo, branch, resolved);
|
|
422
483
|
}
|
|
423
|
-
mergeBranch(branch, into) {
|
|
424
|
-
return mergeBranch(this.client, this.repo, branch, into);
|
|
484
|
+
mergeBranch(branch, into, opts) {
|
|
485
|
+
return mergeBranch(this.client, this.repo, branch, into, opts);
|
|
425
486
|
}
|
|
426
487
|
isMerged(branch, into) {
|
|
427
488
|
const resolved = into ?? "main";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["listBranchesOp","createBranchOp","deleteBranchOp","getBranchDiffOp","mergeBranchOp","isMergedOp","getDefaultBranchOp"],"sources":["../../../src/providers/github/app-auth.ts","../../../src/providers/github/capabilities.ts","../../../src/providers/github/apply-plan.ts","../../../src/providers/github/branch-ops.ts","../../../src/providers/github/reader.ts","../../../src/providers/github/provider.ts","../../../src/providers/github/factory.ts","../../../src/providers/github/types.ts"],"sourcesContent":["import { createPrivateKey, createSign } from 'node:crypto'\n\n/**\n * GitHub App authentication helpers.\n *\n * Two entry points:\n *\n * - {@link signAppJwt} — mint a short-lived (10 min) GitHub App JWT from\n * `appId` + `privateKey`. Used to authenticate app-level endpoints\n * (listing installations, creating installation tokens).\n *\n * - {@link exchangeInstallationToken} — exchange an app JWT for a\n * per-installation access token that can be passed straight to\n * `Octokit({ auth: token })`. Installation tokens last ~1 hour and\n * must be refreshed.\n *\n * Both helpers are pure — they never import `@octokit/rest` or\n * `@octokit/auth-app`. Callers that want auto-refresh behaviour should\n * either wire `@octokit/auth-app` as the `authStrategy` when constructing\n * their own Octokit (see the embedding guide), or call\n * `exchangeInstallationToken` on their own schedule.\n */\n\nexport interface AppAuthConfig {\n /** GitHub App ID (numeric, from the app's settings page). */\n appId: number\n /** PEM-encoded private key — the contents of the `.pem` the app issued. */\n privateKey: string\n /** Installation the token should be scoped to. */\n installationId: number\n}\n\nexport interface InstallationTokenResult {\n /** Opaque bearer token — pass to `new Octokit({ auth: token })`. */\n token: string\n /** ISO 8601 expiry. Installation tokens expire after ~1 hour. */\n expiresAt: string\n}\n\n/**\n * Sign a GitHub App JWT.\n *\n * GitHub's spec: RS256 (RSASSA-PKCS1-v1_5), 10-minute max lifetime,\n * `iat` 60 seconds in the past to cover small clock skew, `iss`\n * set to the numeric app ID.\n */\nfunction base64UrlEncode(obj: unknown): string {\n return Buffer.from(JSON.stringify(obj), 'utf8').toString('base64url')\n}\n\nexport function signAppJwt(config: Pick<AppAuthConfig, 'appId' | 'privateKey'>): string {\n const now = Math.floor(Date.now() / 1000)\n const header = { alg: 'RS256', typ: 'JWT' }\n const payload = {\n iat: now - 60,\n exp: now + 9 * 60,\n iss: String(config.appId),\n }\n\n const toSign = `${base64UrlEncode(header)}.${base64UrlEncode(payload)}`\n const keyObject = createPrivateKey({ key: config.privateKey, format: 'pem' })\n const signer = createSign('RSA-SHA256')\n signer.update(toSign)\n signer.end()\n const signature = signer.sign(keyObject).toString('base64url')\n\n return `${toSign}.${signature}`\n}\n\n/**\n * Exchange an App JWT for an installation-scoped access token by calling\n * GitHub's `POST /app/installations/{id}/access_tokens` endpoint.\n *\n * Uses `fetch` (Node ≥22 has it native) so the helper stays dependency-\n * free. Throws on non-2xx responses with the GitHub-returned message.\n */\nexport async function exchangeInstallationToken(\n config: AppAuthConfig,\n opts: { baseUrl?: string, fetchImpl?: typeof globalThis.fetch } = {},\n): Promise<InstallationTokenResult> {\n const jwt = signAppJwt(config)\n const baseUrl = opts.baseUrl ?? 'https://api.github.com'\n const fetchImpl = opts.fetchImpl ?? globalThis.fetch\n\n const url = `${baseUrl}/app/installations/${config.installationId}/access_tokens`\n const response = await fetchImpl(url, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${jwt}`,\n Accept: 'application/vnd.github+json',\n 'X-GitHub-Api-Version': '2022-11-28',\n },\n })\n\n if (!response.ok) {\n const body = await response.text().catch(() => '')\n throw new Error(\n `GitHub installation-token exchange failed: ${response.status} ${response.statusText}${body ? ` — ${body}` : ''}`,\n )\n }\n\n const data = await response.json() as { token: string, expires_at: string }\n return { token: data.token, expiresAt: data.expires_at }\n}\n","import type { ProviderCapabilities } from '../../core/contracts/index.js'\n\n/**\n * Capability set for GitHubProvider.\n *\n * GitHub over the Git Data API has no working tree, so local worktree\n * features, source-file access and AST scans are unavailable. Push /\n * PR operations are free because every commit goes straight to the\n * remote. Branch protection detection uses the Repos API.\n *\n * Tools that require `astScan`, `sourceRead` or `sourceWrite` must\n * gracefully reject (with `capability_required`) when running against\n * a GitHubProvider — this is the mechanism behind phase 6's normalize\n * capability-gate.\n */\nexport const GITHUB_CAPABILITIES: ProviderCapabilities = {\n localWorktree: false,\n sourceRead: false,\n sourceWrite: false,\n pushRemote: true,\n branchProtection: true,\n pullRequestFallback: true,\n astScan: false,\n}\n","import { CONTENTRAIN_BRANCH } from '@contentrain/types'\nimport type { ApplyPlanInput, Commit, FileChange } from '../../core/contracts/index.js'\nimport { isNotFoundError, resolveRepoPath } from '../shared/index.js'\nimport type { GitHubClient } from './client.js'\nimport type { RepoRef } from './types.js'\n\ninterface TreeEntry {\n path: string\n mode: '100644' | '100755' | '040000' | '160000' | '120000'\n type: 'blob' | 'tree' | 'commit'\n sha: string | null\n}\n\n/**\n * Apply a plan to a GitHub repository as a single atomic commit via the\n * Git Data API. High-level flow:\n *\n * 1. Resolve the base commit SHA — either the current HEAD of the target\n * branch, or the HEAD of `input.base` (or the repo's default branch)\n * when the target branch does not yet exist.\n * 2. Read the base tree SHA from that commit.\n * 3. Walk `input.changes` in parallel — create a blob per non-null\n * content, emit a tree entry with `sha: null` for each deletion.\n * 4. Create a new tree layered on top of the base tree with the collected\n * entries.\n * 5. Create the commit (tree, parents, author).\n * 6. Update an existing branch ref or create a new one pointing at the\n * commit.\n *\n * No working tree, no transaction — the commit is durable as soon as the\n * final ref update returns.\n */\nexport async function applyPlanToGitHub(\n client: GitHubClient,\n repo: RepoRef,\n input: ApplyPlanInput,\n): Promise<Commit> {\n const { baseSha, branchExists } = await resolveBaseSha(client, repo, input.branch, input.base)\n\n const baseCommit = await client.rest.git.getCommit({\n owner: repo.owner,\n repo: repo.name,\n commit_sha: baseSha,\n })\n const baseTreeSha = baseCommit.data.tree.sha\n\n const treeEntries = await Promise.all(\n input.changes.map(change => buildTreeEntry(client, repo, change)),\n )\n\n const tree = await client.rest.git.createTree({\n owner: repo.owner,\n repo: repo.name,\n base_tree: baseTreeSha,\n tree: treeEntries,\n })\n\n const timestamp = new Date().toISOString()\n const commit = await client.rest.git.createCommit({\n owner: repo.owner,\n repo: repo.name,\n message: input.message,\n tree: tree.data.sha,\n parents: [baseSha],\n author: {\n name: input.author.name,\n email: input.author.email,\n date: timestamp,\n },\n })\n\n if (branchExists) {\n await client.rest.git.updateRef({\n owner: repo.owner,\n repo: repo.name,\n ref: `heads/${input.branch}`,\n sha: commit.data.sha,\n })\n } else {\n await client.rest.git.createRef({\n owner: repo.owner,\n repo: repo.name,\n ref: `refs/heads/${input.branch}`,\n sha: commit.data.sha,\n })\n }\n\n return {\n sha: commit.data.sha,\n message: commit.data.message,\n author: {\n name: commit.data.author?.name ?? input.author.name,\n email: commit.data.author?.email ?? input.author.email,\n },\n timestamp: commit.data.author?.date ?? timestamp,\n }\n}\n\nasync function buildTreeEntry(\n client: GitHubClient,\n repo: RepoRef,\n change: FileChange,\n): Promise<TreeEntry> {\n const path = resolveRepoPath(repo.contentRoot, change.path)\n if (change.content === null) {\n return { path, mode: '100644', type: 'blob', sha: null }\n }\n const blob = await client.rest.git.createBlob({\n owner: repo.owner,\n repo: repo.name,\n content: change.content,\n encoding: 'utf-8',\n })\n return { path, mode: '100644', type: 'blob', sha: blob.data.sha }\n}\n\nasync function resolveBaseSha(\n client: GitHubClient,\n repo: RepoRef,\n branch: string,\n base: string | undefined,\n): Promise<{ baseSha: string, branchExists: boolean }> {\n try {\n const ref = await client.rest.git.getRef({\n owner: repo.owner,\n repo: repo.name,\n ref: `heads/${branch}`,\n })\n return { baseSha: ref.data.object.sha, branchExists: true }\n } catch (error) {\n if (!isNotFoundError(error)) throw error\n }\n\n // Invariant: feature branches always fork from the Contentrain\n // content-tracking branch. Callers that genuinely want to bypass this\n // must pass `base` explicitly. The repository's default branch\n // (main / master / trunk) is NOT the fallback — that would create a\n // split-brain where remote writes derive from a different ref than\n // local writes, which the LocalProvider transaction path forbids.\n const baseRefName = base ?? CONTENTRAIN_BRANCH\n\n const baseRef = await client.rest.git.getRef({\n owner: repo.owner,\n repo: repo.name,\n ref: `heads/${baseRefName}`,\n })\n return { baseSha: baseRef.data.object.sha, branchExists: false }\n}\n","import type { Branch, FileDiff, MergeResult } from '../../core/contracts/index.js'\nimport type { GitHubClient } from './client.js'\nimport type { RepoRef } from './types.js'\n\n/**\n * Branch/merge/diff helpers backed by the Repos and Git Data APIs.\n *\n * Pure functions so they can be composed into `GitHubProvider` or used\n * standalone. All throw on non-404 errors; 404s collapse to empty-ish\n * results where that matches the `RepoProvider` contract (e.g. a\n * missing branch prefix yields `[]` rather than raising).\n */\n\nexport async function getDefaultBranch(client: GitHubClient, repo: RepoRef): Promise<string> {\n const response = await client.rest.repos.get({ owner: repo.owner, repo: repo.name })\n return response.data.default_branch\n}\n\nexport async function listBranches(\n client: GitHubClient,\n repo: RepoRef,\n prefix?: string,\n): Promise<Branch[]> {\n const branches: Branch[] = []\n const iterator = client.paginate.iterator(client.rest.repos.listBranches, {\n owner: repo.owner,\n repo: repo.name,\n per_page: 100,\n })\n for await (const page of iterator) {\n for (const b of page.data) {\n if (prefix && !b.name.startsWith(prefix)) continue\n branches.push({ name: b.name, sha: b.commit.sha, protected: b.protected })\n }\n }\n return branches\n}\n\nexport async function createBranch(\n client: GitHubClient,\n repo: RepoRef,\n name: string,\n fromRef: string,\n): Promise<void> {\n const base = await client.rest.git.getRef({\n owner: repo.owner,\n repo: repo.name,\n ref: `heads/${fromRef}`,\n })\n await client.rest.git.createRef({\n owner: repo.owner,\n repo: repo.name,\n ref: `refs/heads/${name}`,\n sha: base.data.object.sha,\n })\n}\n\nexport async function deleteBranch(\n client: GitHubClient,\n repo: RepoRef,\n name: string,\n): Promise<void> {\n await client.rest.git.deleteRef({\n owner: repo.owner,\n repo: repo.name,\n ref: `heads/${name}`,\n })\n}\n\nexport async function getBranchDiff(\n client: GitHubClient,\n repo: RepoRef,\n branch: string,\n base: string,\n): Promise<FileDiff[]> {\n const response = await client.rest.repos.compareCommits({\n owner: repo.owner,\n repo: repo.name,\n base,\n head: branch,\n })\n const files = response.data.files ?? []\n return files.map(f => ({\n path: f.filename,\n status: normaliseStatus(f.status),\n before: null,\n after: null,\n }))\n}\n\nexport async function mergeBranch(\n client: GitHubClient,\n repo: RepoRef,\n branch: string,\n into: string,\n): Promise<MergeResult> {\n try {\n const response = await client.rest.repos.merge({\n owner: repo.owner,\n repo: repo.name,\n base: into,\n head: branch,\n })\n return { merged: true, sha: response.data.sha, pullRequestUrl: null }\n } catch (error) {\n if (isNotModified(error)) {\n return { merged: true, sha: null, pullRequestUrl: null }\n }\n throw error\n }\n}\n\nexport async function isMerged(\n client: GitHubClient,\n repo: RepoRef,\n branch: string,\n into: string,\n): Promise<boolean> {\n const response = await client.rest.repos.compareCommits({\n owner: repo.owner,\n repo: repo.name,\n base: into,\n head: branch,\n })\n return response.data.ahead_by === 0\n}\n\nfunction normaliseStatus(status: string): FileDiff['status'] {\n if (status === 'added') return 'added'\n if (status === 'removed') return 'removed'\n return 'modified'\n}\n\nfunction isNotModified(error: unknown): boolean {\n return typeof error === 'object' && error !== null && (error as { status?: number }).status === 204\n}\n","import type { RepoReader } from '../../core/contracts/index.js'\nimport { isNotFoundError, resolveRepoPath } from '../shared/index.js'\nimport type { GitHubClient } from './client.js'\nimport type { RepoRef } from './types.js'\n\n/**\n * GitHubReader — `RepoReader` backed by the GitHub Repos + Git Data APIs.\n *\n * Reads pass through `repos.getContent`; directories return a list of\n * names, files return decoded UTF-8 text. Files larger than ~1 MB are\n * fetched by blob SHA through `git.getBlob` because `getContent` omits\n * the body in that case.\n *\n * `ref` is forwarded verbatim and may be a branch name, tag name or\n * commit SHA. When omitted, GitHub resolves to the repository's default\n * branch — which is usually wrong for Contentrain flows, so callers\n * should always pass the explicit `contentrain` tracking branch.\n */\nexport class GitHubReader implements RepoReader {\n constructor(\n private readonly client: GitHubClient,\n private readonly repo: RepoRef,\n ) {}\n\n async readFile(path: string, ref?: string): Promise<string> {\n const repoPath = resolveRepoPath(this.repo.contentRoot, path)\n const response = await this.client.rest.repos.getContent({\n owner: this.repo.owner,\n repo: this.repo.name,\n path: repoPath,\n ref,\n })\n const data = response.data\n if (Array.isArray(data)) {\n throw new Error(`GitHubReader: path \"${path}\" is a directory, not a file`)\n }\n if (data.type !== 'file') {\n throw new Error(`GitHubReader: path \"${path}\" is a ${data.type}, not a file`)\n }\n\n // GitHub omits content for files > 1 MB — fall back to blob fetch.\n if (data.content === '' && data.size > 0) {\n const blob = await this.client.rest.git.getBlob({\n owner: this.repo.owner,\n repo: this.repo.name,\n file_sha: data.sha,\n })\n if (blob.data.encoding !== 'base64') {\n throw new Error(`GitHubReader: unexpected blob encoding \"${blob.data.encoding}\" for ${path}`)\n }\n return Buffer.from(blob.data.content, 'base64').toString('utf-8')\n }\n\n if (data.encoding !== 'base64') {\n throw new Error(`GitHubReader: unexpected encoding \"${data.encoding}\" for ${path}`)\n }\n return Buffer.from(data.content, 'base64').toString('utf-8')\n }\n\n async listDirectory(path: string, ref?: string): Promise<string[]> {\n const repoPath = resolveRepoPath(this.repo.contentRoot, path)\n try {\n const response = await this.client.rest.repos.getContent({\n owner: this.repo.owner,\n repo: this.repo.name,\n path: repoPath,\n ref,\n })\n const data = response.data\n if (!Array.isArray(data)) return []\n return data.map(entry => entry.name)\n } catch (error) {\n if (isNotFoundError(error)) return []\n throw error\n }\n }\n\n async fileExists(path: string, ref?: string): Promise<boolean> {\n const repoPath = resolveRepoPath(this.repo.contentRoot, path)\n try {\n await this.client.rest.repos.getContent({\n owner: this.repo.owner,\n repo: this.repo.name,\n path: repoPath,\n ref,\n })\n return true\n } catch (error) {\n if (isNotFoundError(error)) return false\n throw error\n }\n }\n}\n","import type {\n ApplyPlanInput,\n Branch,\n Commit,\n FileDiff,\n MergeResult,\n ProviderCapabilities,\n RepoProvider,\n} from '../../core/contracts/index.js'\nimport { applyPlanToGitHub } from './apply-plan.js'\nimport {\n createBranch as createBranchOp,\n deleteBranch as deleteBranchOp,\n getBranchDiff as getBranchDiffOp,\n getDefaultBranch as getDefaultBranchOp,\n isMerged as isMergedOp,\n listBranches as listBranchesOp,\n mergeBranch as mergeBranchOp,\n} from './branch-ops.js'\nimport { GITHUB_CAPABILITIES } from './capabilities.js'\nimport type { GitHubClient } from './client.js'\nimport { GitHubReader } from './reader.js'\nimport type { RepoRef } from './types.js'\n\n/**\n * GitHubProvider — `RepoProvider` backed by the Octokit-driven GitHub\n * REST + Git Data APIs.\n *\n * The provider is transport-agnostic; it only talks to an `Octokit`\n * instance passed into the constructor. The `createGitHubProvider`\n * helper in `factory.ts` wraps the dynamic import so consumers never\n * have to touch Octokit directly.\n */\nexport class GitHubProvider implements RepoProvider {\n readonly capabilities: ProviderCapabilities = GITHUB_CAPABILITIES\n private readonly reader: GitHubReader\n\n constructor(\n private readonly client: GitHubClient,\n public readonly repo: RepoRef,\n ) {\n this.reader = new GitHubReader(client, repo)\n }\n\n readFile(path: string, ref?: string): Promise<string> {\n return this.reader.readFile(path, ref)\n }\n listDirectory(path: string, ref?: string): Promise<string[]> {\n return this.reader.listDirectory(path, ref)\n }\n fileExists(path: string, ref?: string): Promise<boolean> {\n return this.reader.fileExists(path, ref)\n }\n\n applyPlan(input: ApplyPlanInput): Promise<Commit> {\n return applyPlanToGitHub(this.client, this.repo, input)\n }\n\n listBranches(prefix?: string): Promise<Branch[]> {\n return listBranchesOp(this.client, this.repo, prefix)\n }\n createBranch(name: string, fromRef?: string): Promise<void> {\n const resolved = fromRef ?? 'main'\n return createBranchOp(this.client, this.repo, name, resolved)\n }\n deleteBranch(name: string): Promise<void> {\n return deleteBranchOp(this.client, this.repo, name)\n }\n getBranchDiff(branch: string, base?: string): Promise<FileDiff[]> {\n const resolved = base ?? 'main'\n return getBranchDiffOp(this.client, this.repo, branch, resolved)\n }\n mergeBranch(branch: string, into: string): Promise<MergeResult> {\n return mergeBranchOp(this.client, this.repo, branch, into)\n }\n isMerged(branch: string, into?: string): Promise<boolean> {\n const resolved = into ?? 'main'\n return isMergedOp(this.client, this.repo, branch, resolved)\n }\n getDefaultBranch(): Promise<string> {\n return getDefaultBranchOp(this.client, this.repo)\n }\n}\n","import type { GitHubClient } from './client.js'\nimport { exchangeInstallationToken } from './app-auth.js'\nimport { GitHubProvider } from './provider.js'\nimport type { GitHubAuth, RepoRef } from './types.js'\n\n/**\n * Create an Octokit-backed `GitHubClient` from an auth configuration.\n *\n * The `@octokit/rest` module is imported dynamically so it stays a pure\n * optional peer dependency — self-hosted MCP on stdio can run without\n * it. If the module is not installed, the import throws with a helpful\n * hint pointing the operator at the peer dependency.\n *\n * Two auth modes:\n *\n * - `pat` — personal access token or fine-grained PAT. Simplest for\n * self-hosted MCP or CI runners.\n * - `app` — GitHub App installation auth. The factory mints a short-\n * lived JWT, exchanges it for an installation token via\n * `exchangeInstallationToken`, and instantiates Octokit with the\n * resulting bearer. The returned token expires in ~1 hour; callers\n * that need auto-refresh should instead inject their own Octokit\n * built with `@octokit/auth-app`'s auth strategy and construct\n * `GitHubProvider` directly. See the embedding guide for trade-offs.\n */\nexport async function createGitHubClient(auth: GitHubAuth): Promise<GitHubClient> {\n let OctokitCtor: typeof import('@octokit/rest').Octokit\n try {\n ({ Octokit: OctokitCtor } = await import('@octokit/rest'))\n } catch (error) {\n throw new Error(\n '@octokit/rest is required for the GitHubProvider but could not be loaded. '\n + 'Install it as a peer dependency: pnpm add @octokit/rest.',\n { cause: error },\n )\n }\n\n if (auth.type === 'pat') {\n return new OctokitCtor({ auth: auth.token })\n }\n\n if (auth.type === 'app') {\n const { token } = await exchangeInstallationToken({\n appId: auth.appId,\n privateKey: auth.privateKey,\n installationId: auth.installationId,\n })\n return new OctokitCtor({ auth: token })\n }\n\n const unknown = auth as { type: string }\n throw new Error(`GitHub auth type \"${unknown.type}\" is not supported. Use \"pat\" or \"app\".`)\n}\n\n/**\n * Factory for the full provider — instantiates an Octokit client and\n * wraps it in a `GitHubProvider`. Consumers who already hold an Octokit\n * instance (HTTP server injecting shared clients, tests, etc.) should\n * instantiate `GitHubProvider` directly instead.\n */\nexport async function createGitHubProvider(opts: { auth: GitHubAuth, repo: RepoRef }): Promise<GitHubProvider> {\n const client = await createGitHubClient(opts.auth)\n return new GitHubProvider(client, opts.repo)\n}\n","import type { CommitAuthor } from '../../core/contracts/index.js'\n\n/**\n * A reference to a GitHub repository.\n *\n * `contentRoot` is the repo-relative directory prefix where Contentrain\n * content lives. For a flat content repo it stays `''`; for a monorepo\n * where Contentrain is embedded (e.g. `apps/web/.contentrain/`) it holds\n * that prefix. All reader/writer paths are joined against it.\n */\nexport interface RepoRef {\n owner: string\n name: string\n contentRoot?: string\n}\n\n/**\n * Authentication options for the GitHub provider.\n *\n * - `pat` — a personal access token or fine-grained PAT. Simplest for\n * self-hosted MCP or CI runners. Phase 5.1 ships with this mode only.\n * - `app` — GitHub App installation auth (JWT + installation token\n * exchange). Planned for Phase 5.2; see `.internal/refactor/\n * 02-studio-handoff.md` S6 for how Studio's hosted MCP plugs in.\n */\nexport type GitHubAuth =\n | { type: 'pat', token: string }\n | {\n type: 'app'\n appId: number\n privateKey: string\n installationId: number\n }\n\n/** Default author used when a call does not provide one. */\nexport const DEFAULT_GITHUB_AUTHOR: CommitAuthor = {\n name: 'Contentrain',\n email: 'ai@contentrain.io',\n}\n"],"mappings":";;;;;;;;;;;AA8CA,SAAS,gBAAgB,KAAsB;AAC7C,QAAO,OAAO,KAAK,KAAK,UAAU,IAAI,EAAE,OAAO,CAAC,SAAS,YAAY;;AAGvE,SAAgB,WAAW,QAA6D;CACtF,MAAM,MAAM,KAAK,MAAM,KAAK,KAAK,GAAG,IAAK;CACzC,MAAM,SAAS;EAAE,KAAK;EAAS,KAAK;EAAO;CAC3C,MAAM,UAAU;EACd,KAAK,MAAM;EACX,KAAK,MAAM;EACX,KAAK,OAAO,OAAO,MAAM;EAC1B;CAED,MAAM,SAAS,GAAG,gBAAgB,OAAO,CAAC,GAAG,gBAAgB,QAAQ;CACrE,MAAM,YAAY,iBAAiB;EAAE,KAAK,OAAO;EAAY,QAAQ;EAAO,CAAC;CAC7E,MAAM,SAAS,WAAW,aAAa;AACvC,QAAO,OAAO,OAAO;AACrB,QAAO,KAAK;AAGZ,QAA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,KAAK,QAAQ,KAAK,MAAM,QAAQ,SAAS;;CAE7D,mBAAoC;AAClC,SAAOC,iBAAmB,KAAK,QAAQ,KAAK,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;ACvDrD,eAAsB,mBAAmB,MAAyC;CAChF,IAAI;AACJ,KAAI;AACF,GAAC,CAAE,SAAS,eAAgB,MAAM,OAAO;UAClC,OAAO;AACd,QAAM,IAAI,MACR,sIAEA,EAAE,OAAO,OAAO,CACjB;;AAGH,KAAI,KAAK,SAAS,MAChB,QAAO,IAAI,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC;AAG9C,KAAI,KAAK,SAAS,OAAO;EACvB,MAAM,EAAE,UAAU,MAAM,0BAA0B;GAChD,OAAO,KAAK;GACZ,YAAY,KAAK;GACjB,gBAAgB,KAAK;GACtB,CAAC;AACF,SAAO,IAAI,YAAY,EAAE,MAAM,OAAO,CAAC;;CAGzC,MAAM,UAAU;AAChB,OAAM,IAAI,MAAM,qBAAqB,QAAQ,KAAK,yCAAyC;;;;;;;;AAS7F,eAAsB,qBAAqB,MAAoE;AAE7G,QAAO,IAAI,eADI,MAAM,mBAAmB,KAAK,KAAK,EAChB,KAAK,KAAK;;;;;AC3B9C,MAAa,wBAAsC;CACjD,MAAM;CACN,OAAO;CACR"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["listBranchesOp","createBranchOp","deleteBranchOp","getBranchDiffOp","mergeBranchOp","isMergedOp","getDefaultBranchOp"],"sources":["../../../src/providers/github/app-auth.ts","../../../src/providers/github/capabilities.ts","../../../src/providers/github/apply-plan.ts","../../../src/providers/github/branch-ops.ts","../../../src/providers/github/reader.ts","../../../src/providers/github/provider.ts","../../../src/providers/github/factory.ts","../../../src/providers/github/types.ts"],"sourcesContent":["import { createPrivateKey, createSign } from 'node:crypto'\n\n/**\n * GitHub App authentication helpers.\n *\n * Two entry points:\n *\n * - {@link signAppJwt} — mint a short-lived (10 min) GitHub App JWT from\n * `appId` + `privateKey`. Used to authenticate app-level endpoints\n * (listing installations, creating installation tokens).\n *\n * - {@link exchangeInstallationToken} — exchange an app JWT for a\n * per-installation access token that can be passed straight to\n * `Octokit({ auth: token })`. Installation tokens last ~1 hour and\n * must be refreshed.\n *\n * Both helpers are pure — they never import `@octokit/rest` or\n * `@octokit/auth-app`. Callers that want auto-refresh behaviour should\n * either wire `@octokit/auth-app` as the `authStrategy` when constructing\n * their own Octokit (see the embedding guide), or call\n * `exchangeInstallationToken` on their own schedule.\n */\n\nexport interface AppAuthConfig {\n /** GitHub App ID (numeric, from the app's settings page). */\n appId: number\n /** PEM-encoded private key — the contents of the `.pem` the app issued. */\n privateKey: string\n /** Installation the token should be scoped to. */\n installationId: number\n}\n\nexport interface InstallationTokenResult {\n /** Opaque bearer token — pass to `new Octokit({ auth: token })`. */\n token: string\n /** ISO 8601 expiry. Installation tokens expire after ~1 hour. */\n expiresAt: string\n}\n\n/**\n * Sign a GitHub App JWT.\n *\n * GitHub's spec: RS256 (RSASSA-PKCS1-v1_5), 10-minute max lifetime,\n * `iat` 60 seconds in the past to cover small clock skew, `iss`\n * set to the numeric app ID.\n */\nfunction base64UrlEncode(obj: unknown): string {\n return Buffer.from(JSON.stringify(obj), 'utf8').toString('base64url')\n}\n\nexport function signAppJwt(config: Pick<AppAuthConfig, 'appId' | 'privateKey'>): string {\n const now = Math.floor(Date.now() / 1000)\n const header = { alg: 'RS256', typ: 'JWT' }\n const payload = {\n iat: now - 60,\n exp: now + 9 * 60,\n iss: String(config.appId),\n }\n\n const toSign = `${base64UrlEncode(header)}.${base64UrlEncode(payload)}`\n const keyObject = createPrivateKey({ key: config.privateKey, format: 'pem' })\n const signer = createSign('RSA-SHA256')\n signer.update(toSign)\n signer.end()\n const signature = signer.sign(keyObject).toString('base64url')\n\n return `${toSign}.${signature}`\n}\n\n/**\n * Exchange an App JWT for an installation-scoped access token by calling\n * GitHub's `POST /app/installations/{id}/access_tokens` endpoint.\n *\n * Uses `fetch` (Node ≥22 has it native) so the helper stays dependency-\n * free. Throws on non-2xx responses with the GitHub-returned message.\n */\nexport async function exchangeInstallationToken(\n config: AppAuthConfig,\n opts: { baseUrl?: string, fetchImpl?: typeof globalThis.fetch } = {},\n): Promise<InstallationTokenResult> {\n const jwt = signAppJwt(config)\n const baseUrl = opts.baseUrl ?? 'https://api.github.com'\n const fetchImpl = opts.fetchImpl ?? globalThis.fetch\n\n const url = `${baseUrl}/app/installations/${config.installationId}/access_tokens`\n const response = await fetchImpl(url, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${jwt}`,\n Accept: 'application/vnd.github+json',\n 'X-GitHub-Api-Version': '2022-11-28',\n },\n })\n\n if (!response.ok) {\n const body = await response.text().catch(() => '')\n throw new Error(\n `GitHub installation-token exchange failed: ${response.status} ${response.statusText}${body ? ` — ${body}` : ''}`,\n )\n }\n\n const data = await response.json() as { token: string, expires_at: string }\n return { token: data.token, expiresAt: data.expires_at }\n}\n","import type { ProviderCapabilities } from '../../core/contracts/index.js'\n\n/**\n * Capability set for GitHubProvider.\n *\n * GitHub over the Git Data API has no working tree, so local worktree\n * features, source-file access and AST scans are unavailable. Push /\n * PR operations are free because every commit goes straight to the\n * remote. Branch protection detection uses the Repos API.\n *\n * Tools that require `astScan`, `sourceRead` or `sourceWrite` must\n * gracefully reject (with `capability_required`) when running against\n * a GitHubProvider — this is the mechanism behind phase 6's normalize\n * capability-gate.\n */\nexport const GITHUB_CAPABILITIES: ProviderCapabilities = {\n localWorktree: false,\n sourceRead: false,\n sourceWrite: false,\n pushRemote: true,\n branchProtection: true,\n pullRequestFallback: true,\n astScan: false,\n}\n","import { CONTENTRAIN_BRANCH } from '@contentrain/types'\nimport type { ApplyPlanInput, Commit, FileChange } from '../../core/contracts/index.js'\nimport { isNotFoundError, resolveRepoPath } from '../shared/index.js'\nimport type { GitHubClient } from './client.js'\nimport type { RepoRef } from './types.js'\n\n// A GitHub Git-tree entry. Writes carry `content` inline (GitHub creates the\n// blob as part of createTree); deletions carry `sha: null`. The two are\n// mutually exclusive — an entry may set `content` OR `sha`, never both.\ntype TreeEntry =\n | { path: string, mode: '100644', type: 'blob', content: string }\n | { path: string, mode: '100644', type: 'blob', sha: null }\n\n/**\n * Apply a plan to a GitHub repository as a single atomic commit via the\n * Git Data API. High-level flow:\n *\n * 1. Resolve the base commit SHA — either the current HEAD of the target\n * branch, or the HEAD of `input.base` (or the repo's default branch)\n * when the target branch does not yet exist.\n * 2. Read the base tree SHA from that commit.\n * 3. Map `input.changes` to tree entries — `content` inline for each write,\n * `sha: null` for each deletion. No per-file blob round trip: GitHub\n * creates the blobs as part of `createTree`, which keeps the write to a\n * fixed 3 mutations (tree + commit + ref) regardless of file count and\n * stays under the mutation-rate secondary limit. Mirrors the GitLab\n * provider, which already inlines content in its commit actions.\n * 4. Create a new tree layered on top of the base tree with the collected\n * entries.\n * 5. Create the commit (tree, parents, author).\n * 6. Update an existing branch ref or create a new one pointing at the\n * commit.\n *\n * No working tree, no transaction — the commit is durable as soon as the\n * final ref update returns.\n */\nexport async function applyPlanToGitHub(\n client: GitHubClient,\n repo: RepoRef,\n input: ApplyPlanInput,\n): Promise<Commit> {\n const { baseSha, branchExists } = await resolveBaseSha(client, repo, input.branch, input.base)\n\n const baseCommit = await client.rest.git.getCommit({\n owner: repo.owner,\n repo: repo.name,\n commit_sha: baseSha,\n })\n const baseTreeSha = baseCommit.data.tree.sha\n\n const treeEntries = input.changes.map(change => buildTreeEntry(repo, change))\n\n const tree = await client.rest.git.createTree({\n owner: repo.owner,\n repo: repo.name,\n base_tree: baseTreeSha,\n tree: treeEntries,\n })\n\n const timestamp = new Date().toISOString()\n const commit = await client.rest.git.createCommit({\n owner: repo.owner,\n repo: repo.name,\n message: input.message,\n tree: tree.data.sha,\n parents: [baseSha],\n author: {\n name: input.author.name,\n email: input.author.email,\n date: timestamp,\n },\n })\n\n if (branchExists) {\n await client.rest.git.updateRef({\n owner: repo.owner,\n repo: repo.name,\n ref: `heads/${input.branch}`,\n sha: commit.data.sha,\n })\n } else {\n await client.rest.git.createRef({\n owner: repo.owner,\n repo: repo.name,\n ref: `refs/heads/${input.branch}`,\n sha: commit.data.sha,\n })\n }\n\n return {\n sha: commit.data.sha,\n message: commit.data.message,\n author: {\n name: commit.data.author?.name ?? input.author.name,\n email: commit.data.author?.email ?? input.author.email,\n },\n timestamp: commit.data.author?.date ?? timestamp,\n }\n}\n\nfunction buildTreeEntry(repo: RepoRef, change: FileChange): TreeEntry {\n const path = resolveRepoPath(repo.contentRoot, change.path)\n if (change.content === null) {\n return { path, mode: '100644', type: 'blob', sha: null }\n }\n // Inline UTF-8 content — the write path never produces binary/base64, so\n // there is no blob-encoding branch to preserve. GitHub creates the blob\n // when the tree is created.\n return { path, mode: '100644', type: 'blob', content: change.content }\n}\n\nasync function resolveBaseSha(\n client: GitHubClient,\n repo: RepoRef,\n branch: string,\n base: string | undefined,\n): Promise<{ baseSha: string, branchExists: boolean }> {\n try {\n const ref = await client.rest.git.getRef({\n owner: repo.owner,\n repo: repo.name,\n ref: `heads/${branch}`,\n })\n return { baseSha: ref.data.object.sha, branchExists: true }\n } catch (error) {\n if (!isNotFoundError(error)) throw error\n }\n\n // Invariant: feature branches always fork from the Contentrain\n // content-tracking branch. Callers that genuinely want to bypass this\n // must pass `base` explicitly. The repository's default branch\n // (main / master / trunk) is NOT the fallback — that would create a\n // split-brain where remote writes derive from a different ref than\n // local writes, which the LocalProvider transaction path forbids.\n const baseRefName = base ?? CONTENTRAIN_BRANCH\n\n const baseRef = await client.rest.git.getRef({\n owner: repo.owner,\n repo: repo.name,\n ref: `heads/${baseRefName}`,\n })\n return { baseSha: baseRef.data.object.sha, branchExists: false }\n}\n","import type { Branch, FileDiff, MergeResult } from '../../core/contracts/index.js'\nimport type { GitHubClient } from './client.js'\nimport type { RepoRef } from './types.js'\n\n/**\n * Branch/merge/diff helpers backed by the Repos and Git Data APIs.\n *\n * Pure functions so they can be composed into `GitHubProvider` or used\n * standalone. All throw on non-404 errors; 404s collapse to empty-ish\n * results where that matches the `RepoProvider` contract (e.g. a\n * missing branch prefix yields `[]` rather than raising).\n */\n\nexport async function getDefaultBranch(client: GitHubClient, repo: RepoRef): Promise<string> {\n const response = await client.rest.repos.get({ owner: repo.owner, repo: repo.name })\n return response.data.default_branch\n}\n\nexport async function listBranches(\n client: GitHubClient,\n repo: RepoRef,\n prefix?: string,\n): Promise<Branch[]> {\n const branches: Branch[] = []\n const iterator = client.paginate.iterator(client.rest.repos.listBranches, {\n owner: repo.owner,\n repo: repo.name,\n per_page: 100,\n })\n for await (const page of iterator) {\n for (const b of page.data) {\n if (prefix && !b.name.startsWith(prefix)) continue\n branches.push({ name: b.name, sha: b.commit.sha, protected: b.protected })\n }\n }\n return branches\n}\n\nexport async function createBranch(\n client: GitHubClient,\n repo: RepoRef,\n name: string,\n fromRef: string,\n): Promise<void> {\n const base = await client.rest.git.getRef({\n owner: repo.owner,\n repo: repo.name,\n ref: `heads/${fromRef}`,\n })\n await client.rest.git.createRef({\n owner: repo.owner,\n repo: repo.name,\n ref: `refs/heads/${name}`,\n sha: base.data.object.sha,\n })\n}\n\nexport async function deleteBranch(\n client: GitHubClient,\n repo: RepoRef,\n name: string,\n): Promise<void> {\n await client.rest.git.deleteRef({\n owner: repo.owner,\n repo: repo.name,\n ref: `heads/${name}`,\n })\n}\n\nexport async function getBranchDiff(\n client: GitHubClient,\n repo: RepoRef,\n branch: string,\n base: string,\n): Promise<FileDiff[]> {\n const response = await client.rest.repos.compareCommits({\n owner: repo.owner,\n repo: repo.name,\n base,\n head: branch,\n })\n const files = response.data.files ?? []\n return files.map(f => ({\n path: f.filename,\n status: normaliseStatus(f.status),\n before: null,\n after: null,\n }))\n}\n\nexport async function mergeBranch(\n client: GitHubClient,\n repo: RepoRef,\n branch: string,\n into: string,\n opts?: { removeSourceBranch?: boolean },\n): Promise<MergeResult> {\n try {\n const response = await client.rest.repos.merge({\n owner: repo.owner,\n repo: repo.name,\n base: into,\n head: branch,\n })\n const remote = await cleanupSourceBranch(client, repo, branch, opts)\n return { merged: true, sha: response.data.sha, pullRequestUrl: null, ...(remote ? { remote } : {}) }\n } catch (error) {\n if (isNotModified(error)) {\n const remote = await cleanupSourceBranch(client, repo, branch, opts)\n return { merged: true, sha: null, pullRequestUrl: null, ...(remote ? { remote } : {}) }\n }\n throw error\n }\n}\n\n/**\n * Best-effort post-merge deletion of the source branch so merged cr/*\n * branches don't pile up on the remote. Opt out per call with\n * `removeSourceBranch: false` (e.g. a driver that owns cleanup separately).\n * Never throws — the merge itself already succeeded.\n */\nasync function cleanupSourceBranch(\n client: GitHubClient,\n repo: RepoRef,\n branch: string,\n opts?: { removeSourceBranch?: boolean },\n): Promise<MergeResult['remote'] | undefined> {\n if (opts?.removeSourceBranch === false) return undefined\n try {\n await deleteBranch(client, repo, branch)\n return { deleted: true }\n } catch (error) {\n const status = (error as { status?: number }).status\n // 404/422: ref already gone (e.g. a concurrent cleanup) — expected no-op.\n if (status === 404 || status === 422) {\n return { deleted: false, skipped: 'not-found' }\n }\n return {\n deleted: false,\n warning: `Could not delete \"${branch}\": ${error instanceof Error ? error.message : String(error)}`,\n }\n }\n}\n\nexport async function isMerged(\n client: GitHubClient,\n repo: RepoRef,\n branch: string,\n into: string,\n): Promise<boolean> {\n const response = await client.rest.repos.compareCommits({\n owner: repo.owner,\n repo: repo.name,\n base: into,\n head: branch,\n })\n return response.data.ahead_by === 0\n}\n\nfunction normaliseStatus(status: string): FileDiff['status'] {\n if (status === 'added') return 'added'\n if (status === 'removed') return 'removed'\n return 'modified'\n}\n\nfunction isNotModified(error: unknown): boolean {\n return typeof error === 'object' && error !== null && (error as { status?: number }).status === 204\n}\n","import type { RepoReader } from '../../core/contracts/index.js'\nimport { isNotFoundError, resolveRepoPath } from '../shared/index.js'\nimport type { GitHubClient } from './client.js'\nimport type { RepoRef } from './types.js'\n\n/**\n * GitHubReader — `RepoReader` backed by the GitHub Repos + Git Data APIs.\n *\n * Reads pass through `repos.getContent`; directories return a list of\n * names, files return decoded UTF-8 text. Files larger than ~1 MB are\n * fetched by blob SHA through `git.getBlob` because `getContent` omits\n * the body in that case.\n *\n * `ref` is forwarded verbatim and may be a branch name, tag name or\n * commit SHA. When omitted, GitHub resolves to the repository's default\n * branch — which is usually wrong for Contentrain flows, so callers\n * should always pass the explicit `contentrain` tracking branch.\n *\n * Pass `{ memoize: true }` to dedupe reads within one operation: a repeated\n * `(path, ref)` returns the in-flight/cached promise instead of a fresh\n * `getContent`. This is OPT-IN and only safe for a SHORT-LIVED, read-only\n * reader — a long-lived reader that outlives a write would serve stale\n * results, so the provider's own reader never enables it. Failed reads are\n * evicted so a transient error is retried, not cached forever.\n */\nexport class GitHubReader implements RepoReader {\n private readonly fileMemo = new Map<string, Promise<string>>()\n private readonly listMemo = new Map<string, Promise<string[]>>()\n private readonly existsMemo = new Map<string, Promise<boolean>>()\n\n constructor(\n private readonly client: GitHubClient,\n private readonly repo: RepoRef,\n private readonly opts?: { memoize?: boolean },\n ) {}\n\n /**\n * Run `fetch` through the given memo when memoization is enabled, keyed by\n * `(ref, repoPath)`. A rejected promise is evicted so the next call retries.\n */\n private memoized<T>(memo: Map<string, Promise<T>>, repoPath: string, ref: string | undefined, fetch: () => Promise<T>): Promise<T> {\n if (!this.opts?.memoize) return fetch()\n const key = `${ref ?? ''}:${repoPath}`\n const cached = memo.get(key)\n if (cached) return cached\n const promise = fetch()\n memo.set(key, promise)\n promise.catch(() => memo.delete(key))\n return promise\n }\n\n async readFile(path: string, ref?: string): Promise<string> {\n const repoPath = resolveRepoPath(this.repo.contentRoot, path)\n return this.memoized(this.fileMemo, repoPath, ref, () => this.readFileUncached(path, repoPath, ref))\n }\n\n private async readFileUncached(path: string, repoPath: string, ref?: string): Promise<string> {\n const response = await this.client.rest.repos.getContent({\n owner: this.repo.owner,\n repo: this.repo.name,\n path: repoPath,\n ref,\n })\n const data = response.data\n if (Array.isArray(data)) {\n throw new Error(`GitHubReader: path \"${path}\" is a directory, not a file`)\n }\n if (data.type !== 'file') {\n throw new Error(`GitHubReader: path \"${path}\" is a ${data.type}, not a file`)\n }\n\n // GitHub omits content for files > 1 MB — fall back to blob fetch.\n if (data.content === '' && data.size > 0) {\n const blob = await this.client.rest.git.getBlob({\n owner: this.repo.owner,\n repo: this.repo.name,\n file_sha: data.sha,\n })\n if (blob.data.encoding !== 'base64') {\n throw new Error(`GitHubReader: unexpected blob encoding \"${blob.data.encoding}\" for ${path}`)\n }\n return Buffer.from(blob.data.content, 'base64').toString('utf-8')\n }\n\n if (data.encoding !== 'base64') {\n throw new Error(`GitHubReader: unexpected encoding \"${data.encoding}\" for ${path}`)\n }\n return Buffer.from(data.content, 'base64').toString('utf-8')\n }\n\n async listDirectory(path: string, ref?: string): Promise<string[]> {\n const repoPath = resolveRepoPath(this.repo.contentRoot, path)\n return this.memoized(this.listMemo, repoPath, ref, async () => {\n try {\n const response = await this.client.rest.repos.getContent({\n owner: this.repo.owner,\n repo: this.repo.name,\n path: repoPath,\n ref,\n })\n const data = response.data\n if (!Array.isArray(data)) return []\n return data.map(entry => entry.name)\n } catch (error) {\n if (isNotFoundError(error)) return []\n throw error\n }\n })\n }\n\n async fileExists(path: string, ref?: string): Promise<boolean> {\n const repoPath = resolveRepoPath(this.repo.contentRoot, path)\n return this.memoized(this.existsMemo, repoPath, ref, async () => {\n try {\n await this.client.rest.repos.getContent({\n owner: this.repo.owner,\n repo: this.repo.name,\n path: repoPath,\n ref,\n })\n return true\n } catch (error) {\n if (isNotFoundError(error)) return false\n throw error\n }\n })\n }\n}\n","import type {\n ApplyPlanInput,\n Branch,\n Commit,\n FileDiff,\n MergeResult,\n ProviderCapabilities,\n RepoProvider,\n} from '../../core/contracts/index.js'\nimport { applyPlanToGitHub } from './apply-plan.js'\nimport {\n createBranch as createBranchOp,\n deleteBranch as deleteBranchOp,\n getBranchDiff as getBranchDiffOp,\n getDefaultBranch as getDefaultBranchOp,\n isMerged as isMergedOp,\n listBranches as listBranchesOp,\n mergeBranch as mergeBranchOp,\n} from './branch-ops.js'\nimport { GITHUB_CAPABILITIES } from './capabilities.js'\nimport type { GitHubClient } from './client.js'\nimport { GitHubReader } from './reader.js'\nimport type { RepoRef } from './types.js'\n\n/**\n * GitHubProvider — `RepoProvider` backed by the Octokit-driven GitHub\n * REST + Git Data APIs.\n *\n * The provider is transport-agnostic; it only talks to an `Octokit`\n * instance passed into the constructor. The `createGitHubProvider`\n * helper in `factory.ts` wraps the dynamic import so consumers never\n * have to touch Octokit directly.\n */\nexport class GitHubProvider implements RepoProvider {\n readonly capabilities: ProviderCapabilities = GITHUB_CAPABILITIES\n private readonly reader: GitHubReader\n\n constructor(\n private readonly client: GitHubClient,\n public readonly repo: RepoRef,\n ) {\n this.reader = new GitHubReader(client, repo)\n }\n\n readFile(path: string, ref?: string): Promise<string> {\n return this.reader.readFile(path, ref)\n }\n listDirectory(path: string, ref?: string): Promise<string[]> {\n return this.reader.listDirectory(path, ref)\n }\n fileExists(path: string, ref?: string): Promise<boolean> {\n return this.reader.fileExists(path, ref)\n }\n\n applyPlan(input: ApplyPlanInput): Promise<Commit> {\n return applyPlanToGitHub(this.client, this.repo, input)\n }\n\n listBranches(prefix?: string): Promise<Branch[]> {\n return listBranchesOp(this.client, this.repo, prefix)\n }\n createBranch(name: string, fromRef?: string): Promise<void> {\n const resolved = fromRef ?? 'main'\n return createBranchOp(this.client, this.repo, name, resolved)\n }\n deleteBranch(name: string): Promise<void> {\n return deleteBranchOp(this.client, this.repo, name)\n }\n getBranchDiff(branch: string, base?: string): Promise<FileDiff[]> {\n const resolved = base ?? 'main'\n return getBranchDiffOp(this.client, this.repo, branch, resolved)\n }\n mergeBranch(branch: string, into: string, opts?: { removeSourceBranch?: boolean }): Promise<MergeResult> {\n return mergeBranchOp(this.client, this.repo, branch, into, opts)\n }\n isMerged(branch: string, into?: string): Promise<boolean> {\n const resolved = into ?? 'main'\n return isMergedOp(this.client, this.repo, branch, resolved)\n }\n getDefaultBranch(): Promise<string> {\n return getDefaultBranchOp(this.client, this.repo)\n }\n}\n","import type { GitHubClient } from './client.js'\nimport { exchangeInstallationToken } from './app-auth.js'\nimport { GitHubProvider } from './provider.js'\nimport type { GitHubAuth, RepoRef } from './types.js'\n\n/**\n * Create an Octokit-backed `GitHubClient` from an auth configuration.\n *\n * The `@octokit/rest` module is imported dynamically so it stays a pure\n * optional peer dependency — self-hosted MCP on stdio can run without\n * it. If the module is not installed, the import throws with a helpful\n * hint pointing the operator at the peer dependency.\n *\n * Two auth modes:\n *\n * - `pat` — personal access token or fine-grained PAT. Simplest for\n * self-hosted MCP or CI runners.\n * - `app` — GitHub App installation auth. The factory mints a short-\n * lived JWT, exchanges it for an installation token via\n * `exchangeInstallationToken`, and instantiates Octokit with the\n * resulting bearer. The returned token expires in ~1 hour; callers\n * that need auto-refresh should instead inject their own Octokit\n * built with `@octokit/auth-app`'s auth strategy and construct\n * `GitHubProvider` directly. See the embedding guide for trade-offs.\n */\nexport async function createGitHubClient(auth: GitHubAuth): Promise<GitHubClient> {\n let OctokitCtor: typeof import('@octokit/rest').Octokit\n try {\n ({ Octokit: OctokitCtor } = await import('@octokit/rest'))\n } catch (error) {\n throw new Error(\n '@octokit/rest is required for the GitHubProvider but could not be loaded. '\n + 'Install it as a peer dependency: pnpm add @octokit/rest.',\n { cause: error },\n )\n }\n\n if (auth.type === 'pat') {\n return new OctokitCtor({ auth: auth.token })\n }\n\n if (auth.type === 'app') {\n const { token } = await exchangeInstallationToken({\n appId: auth.appId,\n privateKey: auth.privateKey,\n installationId: auth.installationId,\n })\n return new OctokitCtor({ auth: token })\n }\n\n const unknown = auth as { type: string }\n throw new Error(`GitHub auth type \"${unknown.type}\" is not supported. Use \"pat\" or \"app\".`)\n}\n\n/**\n * Factory for the full provider — instantiates an Octokit client and\n * wraps it in a `GitHubProvider`. Consumers who already hold an Octokit\n * instance (HTTP server injecting shared clients, tests, etc.) should\n * instantiate `GitHubProvider` directly instead.\n */\nexport async function createGitHubProvider(opts: { auth: GitHubAuth, repo: RepoRef }): Promise<GitHubProvider> {\n const client = await createGitHubClient(opts.auth)\n return new GitHubProvider(client, opts.repo)\n}\n","import type { CommitAuthor } from '../../core/contracts/index.js'\n\n/**\n * A reference to a GitHub repository.\n *\n * `contentRoot` is the repo-relative directory prefix where Contentrain\n * content lives. For a flat content repo it stays `''`; for a monorepo\n * where Contentrain is embedded (e.g. `apps/web/.contentrain/`) it holds\n * that prefix. All reader/writer paths are joined against it.\n */\nexport interface RepoRef {\n owner: string\n name: string\n contentRoot?: string\n}\n\n/**\n * Authentication options for the GitHub provider.\n *\n * - `pat` — a personal access token or fine-grained PAT. Simplest for\n * self-hosted MCP or CI runners. Phase 5.1 ships with this mode only.\n * - `app` — GitHub App installation auth (JWT + installation token\n * exchange). Planned for Phase 5.2; see `.internal/refactor/\n * 02-studio-handoff.md` S6 for how Studio's hosted MCP plugs in.\n */\nexport type GitHubAuth =\n | { type: 'pat', token: string }\n | {\n type: 'app'\n appId: number\n privateKey: string\n installationId: number\n }\n\n/** Default author used when a call does not provide one. */\nexport const DEFAULT_GITHUB_AUTHOR: CommitAuthor = {\n name: 'Contentrain',\n email: 'ai@contentrain.io',\n}\n"],"mappings":";;;;;;;;;;;AA8CA,SAAS,gBAAgB,KAAsB;AAC7C,QAAO,OAAO,KAAK,KAAK,UAAU,IAAI,EAAE,OAAO,CAAC,SAAS,YAAY;;AAGvE,SAAgB,WAAW,QAA6D;CACtF,MAAM,MAAM,KAAK,MAAM,KAAK,KAAK,GAAG,IAAK;CACzC,MAAM,SAAS;EAAE,KAAK;EAAS,KAAK;EAAO;CAC3C,MAAM,UAAU;EACd,KAAK,MAAM;EACX,KAAK,MAAM;EACX,KAAK,OAAO,OAAO,MAAM;EAC1B;CAED,MAAM,SAAS,GAAG,gBAAgB,OAAO,CAAC,GAAG,gBAAgB,QAAQ;CACrE,MAAM,YAAY,iBAAiB;EAAE,KAAK,OAAO;EAAY,QAAQ;EAAO,CAAC;CAC7E,MAAM,SAAS,WAAW,aAAa;AACvC,QAAO,OAAO,OAAO;AACrB,QAAO,K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BAAoC;AAClC,SAAOC,iBAAmB,KAAK,QAAQ,KAAK,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;ACvDrD,eAAsB,mBAAmB,MAAyC;CAChF,IAAI;AACJ,KAAI;AACF,GAAC,CAAE,SAAS,eAAgB,MAAM,OAAO;UAClC,OAAO;AACd,QAAM,IAAI,MACR,sIAEA,EAAE,OAAO,OAAO,CACjB;;AAGH,KAAI,KAAK,SAAS,MAChB,QAAO,IAAI,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC;AAG9C,KAAI,KAAK,SAAS,OAAO;EACvB,MAAM,EAAE,UAAU,MAAM,0BAA0B;GAChD,OAAO,KAAK;GACZ,YAAY,KAAK;GACjB,gBAAgB,KAAK;GACtB,CAAC;AACF,SAAO,IAAI,YAAY,EAAE,MAAM,OAAO,CAAC;;CAGzC,MAAM,UAAU;AAChB,OAAM,IAAI,MAAM,qBAAqB,QAAQ,KAAK,yCAAyC;;;;;;;;AAS7F,eAAsB,qBAAqB,MAAoE;AAE7G,QAAO,IAAI,eADI,MAAM,mBAAmB,KAAK,KAAK,EAChB,KAAK,KAAK;;;;;AC3B9C,MAAa,wBAAsC;CACjD,MAAM;CACN,OAAO;CACR"}
|
|
@@ -98,7 +98,9 @@ declare class GitLabProvider implements RepoProvider {
|
|
|
98
98
|
createBranch(name: string, fromRef?: string): Promise<void>;
|
|
99
99
|
deleteBranch(name: string): Promise<void>;
|
|
100
100
|
getBranchDiff(branch: string, base?: string): Promise<FileDiff[]>;
|
|
101
|
-
mergeBranch(branch: string, into: string
|
|
101
|
+
mergeBranch(branch: string, into: string, opts?: {
|
|
102
|
+
removeSourceBranch?: boolean;
|
|
103
|
+
}): Promise<MergeResult>;
|
|
102
104
|
isMerged(branch: string, into?: string): Promise<boolean>;
|
|
103
105
|
getDefaultBranch(): Promise<string>;
|
|
104
106
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/providers/gitlab/capabilities.ts","../../../src/providers/gitlab/client.ts","../../../src/providers/gitlab/types.ts","../../../src/providers/gitlab/provider.ts","../../../src/providers/gitlab/factory.ts","../../../src/providers/gitlab/reader.ts"],"mappings":";;;;;;;AAYA;;;;;;;cAAa,mBAAA,EAAqB,oBAAA;;;;;;AAAlC;;;;;;KCDY,YAAA,GAAe,YAAA,QAAoB,MAAA;;;;;;ADC/C;;;;;;;;ACDA;;;;UCMiB,UAAA;EACf,SAAA;EACA,WAAA;EACA,IAAA;AAAA;;;;;;;;;AAaF;;KAAY,UAAA;EACN,IAAA;EAAa,KAAA;AAAA;EACb,IAAA;EAAe,UAAA;AAAA;EACf,IAAA;EAAa,QAAA;AAAA;AAGnB;AAAA,cAAa,qBAAA,EAAuB,YAAA;;;;AF3BpC;;;;;;;;ACDA;;;;cE0Ba,cAAA,YAA0B,YAAA;EAAA,iBAKlB,MAAA;EAAA,SACD,OAAA,EAAS,UAAA;EAAA,SALlB,YAAA,EAAc,oBAAA;EAAA,iBACN,MAAA;cAGE,MAAA,EAAQ,YAAA,EACT,OAAA,EAAS,UAAA;EAK3B,QAAA,CAAS,IAAA,UAAc,GAAA,YAAe,OAAA;EAGtC,aAAA,CAAc,IAAA,UAAc,GAAA,YAAe,OAAA;EAG3C,UAAA,CAAW,IAAA,UAAc,GAAA,YAAe,OAAA;EAIxC,SAAA,CAAU,KAAA,EAAO,cAAA,GAAiB,OAAA,CAAQ,MAAA;EAI1C,YAAA,CAAa,MAAA,YAAkB,OAAA,CAAQ,MAAA;EAGjC,YAAA,CAAa,IAAA,UAAc,OAAA,YAAmB,OAAA;EAIpD,YAAA,CAAa,IAAA,WAAe,OAAA;EAGtB,aAAA,CAAc,MAAA,UAAgB,IAAA,YAAgB,OAAA,CAAQ,QAAA;EAI5D,WAAA,CAAY,MAAA,UAAgB,IAAA,
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/providers/gitlab/capabilities.ts","../../../src/providers/gitlab/client.ts","../../../src/providers/gitl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AAA;;;;AHvEtB;;;;;;;;ACDA;;;iBGKsB,kBAAA,CACpB,IAAA,EAAM,UAAA,EACN,IAAA,YACC,OAAA,CAAQ,YAAA;;;;;AFFX;;iBEwCsB,oBAAA,CACpB,IAAA;EAAQ,IAAA,EAAM,UAAA;EAAY,OAAA,EAAS,UAAA;AAAA,IAClC,OAAA,CAAQ,cAAA;;;;AJ/CX;;;;;;;;ACDA;;;;;;cISa,YAAA,YAAwB,UAAA;EAAA,iBAEhB,MAAA;EAAA,iBACA,OAAA;cADA,MAAA,EAAQ,YAAA,EACR,OAAA,EAAS,UAAA;EAGtB,QAAA,CAAS,IAAA,UAAc,GAAA,YAAe,OAAA;EAatC,aAAA,CAAc,IAAA,UAAc,GAAA,YAAe,OAAA;EAoB3C,UAAA,CAAW,IAAA,UAAc,GAAA,YAAe,OAAA;EAAA,QA8BhC,iBAAA;AAAA"}
|
|
@@ -152,7 +152,7 @@ async function getBranchDiff(client, project, branch, base) {
|
|
|
152
152
|
after: null
|
|
153
153
|
}));
|
|
154
154
|
}
|
|
155
|
-
async function mergeBranch(client, project, branch, into) {
|
|
155
|
+
async function mergeBranch(client, project, branch, into, opts) {
|
|
156
156
|
const mr = await client.MergeRequests.create(project.projectId, branch, into, `[contentrain] merge ${branch} → ${into}`, { removeSourceBranch: false });
|
|
157
157
|
const accepted = await client.MergeRequests.accept(project.projectId, mr.iid, {
|
|
158
158
|
shouldRemoveSourceBranch: false,
|
|
@@ -160,10 +160,26 @@ async function mergeBranch(client, project, branch, into) {
|
|
|
160
160
|
});
|
|
161
161
|
const mergeSha = accepted.merge_commit_sha ?? accepted.sha ?? null;
|
|
162
162
|
const webUrl = mr.web_url ?? null;
|
|
163
|
+
const merged = mergeSha !== null;
|
|
164
|
+
let remote;
|
|
165
|
+
if (merged && opts?.removeSourceBranch !== false) try {
|
|
166
|
+
await deleteBranch(client, project, branch);
|
|
167
|
+
remote = { deleted: true };
|
|
168
|
+
} catch (error) {
|
|
169
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
170
|
+
remote = /404|not found/i.test(message) ? {
|
|
171
|
+
deleted: false,
|
|
172
|
+
skipped: "not-found"
|
|
173
|
+
} : {
|
|
174
|
+
deleted: false,
|
|
175
|
+
warning: `Could not delete "${branch}": ${message}`
|
|
176
|
+
};
|
|
177
|
+
}
|
|
163
178
|
return {
|
|
164
|
-
merged
|
|
179
|
+
merged,
|
|
165
180
|
sha: mergeSha,
|
|
166
|
-
pullRequestUrl: webUrl
|
|
181
|
+
pullRequestUrl: webUrl,
|
|
182
|
+
...remote ? { remote } : {}
|
|
167
183
|
};
|
|
168
184
|
}
|
|
169
185
|
async function isMerged(client, project, branch, into) {
|
|
@@ -289,8 +305,8 @@ var GitLabProvider = class {
|
|
|
289
305
|
const resolved = base ?? await getDefaultBranch(this.client, this.project);
|
|
290
306
|
return getBranchDiff(this.client, this.project, branch, resolved);
|
|
291
307
|
}
|
|
292
|
-
mergeBranch(branch, into) {
|
|
293
|
-
return mergeBranch(this.client, this.project, branch, into);
|
|
308
|
+
mergeBranch(branch, into, opts) {
|
|
309
|
+
return mergeBranch(this.client, this.project, branch, into, opts);
|
|
294
310
|
}
|
|
295
311
|
async isMerged(branch, into) {
|
|
296
312
|
const resolved = into ?? await getDefaultBranch(this.client, this.project);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["listBranchesOp","getDefaultBranchOp","createBranchOp","deleteBranchOp","getBranchDiffOp","mergeBranchOp","isMergedOp"],"sources":["../../../src/providers/gitlab/capabilities.ts","../../../src/providers/gitlab/apply-plan.ts","../../../src/providers/gitlab/branch-ops.ts","../../../src/providers/gitlab/reader.ts","../../../src/providers/gitlab/provider.ts","../../../src/providers/gitlab/factory.ts","../../../src/providers/gitlab/types.ts"],"sourcesContent":["import type { ProviderCapabilities } from '../../core/contracts/index.js'\n\n/**\n * Capability set for GitLabProvider.\n *\n * GitLab over REST has no working tree, so local worktree features,\n * source-file access and AST scans are unavailable. Push, merge and\n * branch-protection detection all work over the API. GitLab enforces\n * merges through merge requests, so `pullRequestFallback` is `true` —\n * `mergeBranch` opens an MR and auto-accepts it to match GitHub's\n * `repos.merge` semantics while still leaving an audit trail.\n */\nexport const GITLAB_CAPABILITIES: ProviderCapabilities = {\n localWorktree: false,\n sourceRead: false,\n sourceWrite: false,\n pushRemote: true,\n branchProtection: true,\n pullRequestFallback: true,\n astScan: false,\n}\n","import { CONTENTRAIN_BRANCH } from '@contentrain/types'\nimport type { ApplyPlanInput, Commit, FileChange } from '../../core/contracts/index.js'\nimport { isNotFoundError, resolveRepoPath } from '../shared/index.js'\nimport type { GitLabClient } from './client.js'\nimport type { ProjectRef } from './types.js'\n\ntype CommitActionType = 'create' | 'update' | 'delete'\n\ninterface CommitAction {\n action: CommitActionType\n filePath: string\n content?: string\n encoding?: 'text' | 'base64'\n}\n\n/**\n * Apply a plan to a GitLab repository as a single atomic commit via the\n * Commits API. High-level flow:\n *\n * 1. Check whether the target branch exists. If it does not, GitLab's\n * `startBranch` option forks a new branch from `input.base` (or the\n * project's default branch) as part of the same commit.\n * 2. For each `FileChange`, figure out the right GitLab action verb\n * (`create` vs `update` vs `delete`) by probing the path against the\n * resolved ref. GitLab validates this server-side and returns a 400\n * for mismatches — we avoid the round trip by getting it right up\n * front.\n * 3. POST `/repository/commits` once with the full action set. No\n * working tree, no multi-call tree-assembly dance — GitLab exposes\n * a richer primitive than the GitHub Git Data API for this case.\n *\n * The commit is durable as soon as the call returns; GitLab's ref\n * update happens inside the same request.\n */\nexport async function applyPlanToGitLab(\n client: GitLabClient,\n project: ProjectRef,\n input: ApplyPlanInput,\n): Promise<Commit> {\n const branchExists = await branchHasRef(client, project, input.branch)\n // Invariant: fork from the Contentrain content-tracking branch, not\n // the repo's default branch. See ApplyPlanInput.base docstring in\n // @contentrain/types.\n const baseBranch = input.base ?? CONTENTRAIN_BRANCH\n\n // Actions are computed against the HEAD of the feature branch when it\n // exists, otherwise against the fork point (baseBranch). GitLab\n // treats `create` / `update` / `delete` as a strict check against the\n // path's existence at that ref.\n const refForActionResolution = branchExists ? input.branch : baseBranch\n const rawActions = await Promise.all(\n input.changes.map(change => resolveAction(client, project, refForActionResolution, change)),\n )\n const actions = rawActions.filter((a): a is CommitAction => a !== null)\n\n if (actions.length === 0) {\n // Nothing to apply. Callers don't generally build empty plans, but\n // if they do we short-circuit before touching the API.\n throw new Error('applyPlanToGitLab: plan contained no applicable actions')\n }\n\n const options: Record<string, unknown> = {\n authorName: input.author.name,\n authorEmail: input.author.email,\n }\n if (!branchExists) {\n options.startBranch = baseBranch\n }\n\n const response = await client.Commits.create(\n project.projectId,\n input.branch,\n input.message,\n actions,\n options,\n )\n\n // Gitbeaker's generic-heavy response type widens string fields to\n // `string | Camelize<…>` — at runtime they are always strings under\n // the default (non-camelize) response mode we use. Cast narrows the\n // shape we actually touch.\n const commit = response as {\n id: string\n message?: string\n author_name?: string\n author_email?: string\n created_at?: string\n }\n const commitTimestamp = toIsoTimestamp(commit.created_at) ?? new Date().toISOString()\n return {\n sha: commit.id,\n message: commit.message ?? input.message,\n author: {\n name: commit.author_name ?? input.author.name,\n email: commit.author_email ?? input.author.email,\n },\n timestamp: commitTimestamp,\n }\n}\n\nasync function resolveAction(\n client: GitLabClient,\n project: ProjectRef,\n ref: string,\n change: FileChange,\n): Promise<CommitAction | null> {\n const filePath = resolveRepoPath(project.contentRoot, change.path)\n const exists = await fileExistsAtRef(client, project, filePath, ref)\n\n if (change.content === null) {\n // Filter out deletes against non-existent files — GitLab returns\n // 400 otherwise. The plan author asked us to \"make this file not\n // exist\", which is already satisfied.\n if (!exists) return null\n return { action: 'delete', filePath }\n }\n\n return {\n action: exists ? 'update' : 'create',\n filePath,\n content: change.content,\n encoding: 'text',\n }\n}\n\nasync function branchHasRef(\n client: GitLabClient,\n project: ProjectRef,\n branch: string,\n): Promise<boolean> {\n try {\n await client.Branches.show(project.projectId, branch)\n return true\n } catch (error) {\n if (isNotFoundError(error)) return false\n throw error\n }\n}\n\nasync function fileExistsAtRef(\n client: GitLabClient,\n project: ProjectRef,\n filePath: string,\n ref: string,\n): Promise<boolean> {\n try {\n await client.RepositoryFiles.show(project.projectId, filePath, ref)\n return true\n } catch (error) {\n if (isNotFoundError(error)) return false\n throw error\n }\n}\n\n\nfunction toIsoTimestamp(raw: unknown): string | null {\n if (typeof raw !== 'string') return null\n const date = new Date(raw)\n if (Number.isNaN(date.getTime())) return null\n return date.toISOString()\n}\n\n","import type { Branch, FileDiff, MergeResult } from '../../core/contracts/index.js'\nimport type { GitLabClient } from './client.js'\nimport type { ProjectRef } from './types.js'\n\n/**\n * Branch / merge / diff helpers backed by the GitLab REST API.\n *\n * Pure functions so they can be composed into `GitLabProvider` or used\n * standalone. 404s collapse to empty-ish results where that matches\n * the `RepoProvider` contract (missing branch prefix → `[]`).\n *\n * Merge semantics: GitLab does not expose a direct branch-to-branch\n * merge endpoint. Every merge flows through a merge request, so\n * `mergeBranch` opens an MR and immediately accepts it. The resulting\n * `MergeResult` mirrors GitHub's `repos.merge` return shape — callers\n * see the same `{ merged, sha, pullRequestUrl }` envelope either way,\n * with the MR URL available for audit.\n */\n\nexport async function getDefaultBranch(\n client: GitLabClient,\n project: ProjectRef,\n): Promise<string> {\n const p = await client.Projects.show(project.projectId) as { default_branch?: string }\n return p.default_branch ?? 'main'\n}\n\nexport async function listBranches(\n client: GitLabClient,\n project: ProjectRef,\n prefix?: string,\n): Promise<Branch[]> {\n // Gitbeaker's `all` supports a `search` string (substring match). For\n // Contentrain's `cr/*` naming the substring case is equivalent to a\n // prefix because the slug never appears anywhere except at the start.\n // Server-side filter + client-side prefix enforcement keeps us\n // correct even if the substring coincidence breaks someday.\n const options: Record<string, unknown> = {\n perPage: 100,\n maxPages: 10,\n }\n if (prefix) options.search = prefix\n\n const rawBranches = await client.Branches.all(project.projectId, options)\n const branches = Array.isArray(rawBranches) ? rawBranches : []\n\n return branches\n .filter((b: { name: string }) => !prefix || b.name.startsWith(prefix))\n .map((b: { name: string, commit: { id: string }, protected?: boolean }) => ({\n name: b.name,\n sha: b.commit.id,\n protected: b.protected ?? false,\n }))\n}\n\nexport async function createBranch(\n client: GitLabClient,\n project: ProjectRef,\n name: string,\n fromRef: string,\n): Promise<void> {\n await client.Branches.create(project.projectId, name, fromRef)\n}\n\nexport async function deleteBranch(\n client: GitLabClient,\n project: ProjectRef,\n name: string,\n): Promise<void> {\n await client.Branches.remove(project.projectId, name)\n}\n\nexport async function getBranchDiff(\n client: GitLabClient,\n project: ProjectRef,\n branch: string,\n base: string,\n): Promise<FileDiff[]> {\n const response = await client.Repositories.compare(\n project.projectId,\n base,\n branch,\n { straight: false },\n )\n const diffs = Array.isArray(response.diffs) ? response.diffs : []\n return diffs.map((d: { new_path: string, old_path: string, new_file?: boolean, deleted_file?: boolean }) => ({\n path: d.new_file ? d.new_path : d.old_path,\n status: d.deleted_file ? 'removed' : d.new_file ? 'added' : 'modified',\n before: null,\n after: null,\n }))\n}\n\nexport async function mergeBranch(\n client: GitLabClient,\n project: ProjectRef,\n branch: string,\n into: string,\n): Promise<MergeResult> {\n // 1. Open MR — GitLab rejects create when source === target or when\n // an MR is already open for this pair. Let the error propagate in\n // those cases; the caller retries or surfaces the message.\n const mr = await client.MergeRequests.create(\n project.projectId,\n branch,\n into,\n `[contentrain] merge ${branch} → ${into}`,\n { removeSourceBranch: false },\n )\n\n // 2. Accept the MR immediately. `shouldRemoveSourceBranch: false`\n // preserves the feature branch so audit/retry logic still has\n // access to it; Studio's cleanup flow deletes it separately.\n const accepted = await client.MergeRequests.accept(\n project.projectId,\n (mr as { iid: number }).iid,\n { shouldRemoveSourceBranch: false, squash: false },\n )\n\n const mergeSha = (accepted as { merge_commit_sha?: string | null, sha?: string | null }).merge_commit_sha\n ?? (accepted as { sha?: string | null }).sha\n ?? null\n const webUrl = (mr as { web_url?: string }).web_url ?? null\n\n return { merged: mergeSha !== null, sha: mergeSha, pullRequestUrl: webUrl }\n}\n\nexport async function isMerged(\n client: GitLabClient,\n project: ProjectRef,\n branch: string,\n into: string,\n): Promise<boolean> {\n // compare(from=into, to=branch) — commits list is empty when branch\n // is fully contained in into (i.e. already merged).\n const response = await client.Repositories.compare(\n project.projectId,\n into,\n branch,\n { straight: false },\n )\n const commits = Array.isArray(response.commits) ? response.commits : []\n return commits.length === 0\n}\n","import type { RepoReader } from '../../core/contracts/index.js'\nimport { isNotFoundError, resolveRepoPath } from '../shared/index.js'\nimport type { GitLabClient } from './client.js'\nimport type { ProjectRef } from './types.js'\n\n/**\n * GitLabReader — `RepoReader` backed by the GitLab REST API.\n *\n * File reads go through `RepositoryFiles.showRaw`, which returns the\n * file content as UTF-8 text (or a `Blob` on browser/edge runtimes we\n * decode with `.text()`). Directory listings go through\n * `Repositories.allRepositoryTrees`. `fileExists` tries the file\n * endpoint first and falls back to a tree listing so directories\n * resolve to `true` as well — matching LocalReader / GitHubReader.\n *\n * `ref` is forwarded verbatim and may be a branch name, tag name or\n * commit SHA. Callers should always pass the explicit `contentrain`\n * tracking branch; GitLab's default resolution is the project's\n * default branch, which is usually wrong for Contentrain flows.\n */\nexport class GitLabReader implements RepoReader {\n constructor(\n private readonly client: GitLabClient,\n private readonly project: ProjectRef,\n ) {}\n\n async readFile(path: string, ref?: string): Promise<string> {\n const repoPath = resolveRepoPath(this.project.contentRoot, path)\n const resolvedRef = ref ?? await this.resolveDefaultRef()\n const raw = await this.client.RepositoryFiles.showRaw(\n this.project.projectId,\n repoPath,\n resolvedRef,\n )\n if (typeof raw === 'string') return raw\n // Browser / edge runtimes return a Blob; decode as UTF-8.\n return (raw as Blob).text()\n }\n\n async listDirectory(path: string, ref?: string): Promise<string[]> {\n const repoPath = resolveRepoPath(this.project.contentRoot, path)\n const resolvedRef = ref ?? await this.resolveDefaultRef()\n try {\n const entries = await this.client.Repositories.allRepositoryTrees(\n this.project.projectId,\n {\n path: repoPath,\n ref: resolvedRef,\n perPage: 100,\n recursive: false,\n },\n )\n return Array.isArray(entries) ? entries.map(e => e.name) : []\n } catch (error) {\n if (isNotFoundError(error)) return []\n throw error\n }\n }\n\n async fileExists(path: string, ref?: string): Promise<boolean> {\n const repoPath = resolveRepoPath(this.project.contentRoot, path)\n const resolvedRef = ref ?? await this.resolveDefaultRef()\n\n // 1. Try as a file — cheap and most common case for Contentrain.\n try {\n await this.client.RepositoryFiles.show(\n this.project.projectId,\n repoPath,\n resolvedRef,\n )\n return true\n } catch (error) {\n if (!isNotFoundError(error)) throw error\n }\n\n // 2. Fall back to a tree listing — directories and empty dirs show\n // up here. Any non-404 result means the path resolves.\n try {\n const entries = await this.client.Repositories.allRepositoryTrees(\n this.project.projectId,\n { path: repoPath, ref: resolvedRef, perPage: 1 },\n )\n return Array.isArray(entries) && entries.length > 0\n } catch (error) {\n if (isNotFoundError(error)) return false\n throw error\n }\n }\n\n private async resolveDefaultRef(): Promise<string> {\n const project = await this.client.Projects.show(this.project.projectId) as { default_branch?: string }\n return project.default_branch ?? 'main'\n }\n}\n\n","import type {\n ApplyPlanInput,\n Branch,\n Commit,\n FileDiff,\n MergeResult,\n ProviderCapabilities,\n RepoProvider,\n} from '../../core/contracts/index.js'\nimport { applyPlanToGitLab } from './apply-plan.js'\nimport {\n createBranch as createBranchOp,\n deleteBranch as deleteBranchOp,\n getBranchDiff as getBranchDiffOp,\n getDefaultBranch as getDefaultBranchOp,\n isMerged as isMergedOp,\n listBranches as listBranchesOp,\n mergeBranch as mergeBranchOp,\n} from './branch-ops.js'\nimport { GITLAB_CAPABILITIES } from './capabilities.js'\nimport type { GitLabClient } from './client.js'\nimport { GitLabReader } from './reader.js'\nimport type { ProjectRef } from './types.js'\n\n/**\n * GitLabProvider — `RepoProvider` backed by the gitbeaker-driven GitLab\n * REST API.\n *\n * Transport-agnostic: the provider only talks to a `GitLabClient`\n * (a `@gitbeaker/rest` `Gitlab` instance). `createGitLabProvider` in\n * `factory.ts` wraps the dynamic import so consumers never touch\n * `@gitbeaker/rest` directly unless they want to.\n *\n * Capability gaps versus `GitHubProvider`: none — both providers\n * expose the same set. GitLab's merge flow routes through an MR under\n * the hood, but `mergeBranch` presents the same `MergeResult` shape.\n */\nexport class GitLabProvider implements RepoProvider {\n readonly capabilities: ProviderCapabilities = GITLAB_CAPABILITIES\n private readonly reader: GitLabReader\n\n constructor(\n private readonly client: GitLabClient,\n public readonly project: ProjectRef,\n ) {\n this.reader = new GitLabReader(client, project)\n }\n\n readFile(path: string, ref?: string): Promise<string> {\n return this.reader.readFile(path, ref)\n }\n listDirectory(path: string, ref?: string): Promise<string[]> {\n return this.reader.listDirectory(path, ref)\n }\n fileExists(path: string, ref?: string): Promise<boolean> {\n return this.reader.fileExists(path, ref)\n }\n\n applyPlan(input: ApplyPlanInput): Promise<Commit> {\n return applyPlanToGitLab(this.client, this.project, input)\n }\n\n listBranches(prefix?: string): Promise<Branch[]> {\n return listBranchesOp(this.client, this.project, prefix)\n }\n async createBranch(name: string, fromRef?: string): Promise<void> {\n const resolved = fromRef ?? await getDefaultBranchOp(this.client, this.project)\n await createBranchOp(this.client, this.project, name, resolved)\n }\n deleteBranch(name: string): Promise<void> {\n return deleteBranchOp(this.client, this.project, name)\n }\n async getBranchDiff(branch: string, base?: string): Promise<FileDiff[]> {\n const resolved = base ?? await getDefaultBranchOp(this.client, this.project)\n return getBranchDiffOp(this.client, this.project, branch, resolved)\n }\n mergeBranch(branch: string, into: string): Promise<MergeResult> {\n return mergeBranchOp(this.client, this.project, branch, into)\n }\n async isMerged(branch: string, into?: string): Promise<boolean> {\n const resolved = into ?? await getDefaultBranchOp(this.client, this.project)\n return isMergedOp(this.client, this.project, branch, resolved)\n }\n getDefaultBranch(): Promise<string> {\n return getDefaultBranchOp(this.client, this.project)\n }\n}\n","import type { GitLabClient } from './client.js'\nimport { GitLabProvider } from './provider.js'\nimport type { GitLabAuth, ProjectRef } from './types.js'\n\n/**\n * Create a gitbeaker-backed `GitLabClient` from an auth configuration.\n *\n * The `@gitbeaker/rest` module is imported dynamically so it stays a\n * pure optional peer dependency — self-hosted MCP on stdio runs fine\n * without it. If the module is not installed, the import throws with\n * a helpful hint pointing the operator at the peer dependency.\n *\n * Supported auth types: `pat`, `oauth`, `job`. All three are thin\n * wrappers over gitbeaker's `token`, `oauthToken`, and `jobToken`\n * constructor options.\n */\nexport async function createGitLabClient(\n auth: GitLabAuth,\n host?: string,\n): Promise<GitLabClient> {\n let GitlabCtor: typeof import('@gitbeaker/rest').Gitlab\n try {\n ({ Gitlab: GitlabCtor } = await import('@gitbeaker/rest'))\n } catch (error) {\n throw new Error(\n '@gitbeaker/rest is required for the GitLabProvider but could not be loaded. '\n + 'Install it as a peer dependency: pnpm add @gitbeaker/rest.',\n { cause: error },\n )\n }\n\n const config: Record<string, unknown> = host ? { host } : {}\n switch (auth.type) {\n case 'pat':\n config.token = auth.token\n break\n case 'oauth':\n config.oauthToken = auth.oauthToken\n break\n case 'job':\n config.jobToken = auth.jobToken\n break\n default: {\n const { type } = auth as { type: string }\n throw new Error(`Unsupported GitLab auth type: \"${type}\"`)\n }\n }\n\n return new GitlabCtor(config) as GitLabClient\n}\n\n/**\n * Factory for the full provider — instantiates a gitbeaker client and\n * wraps it in a `GitLabProvider`. Consumers who already hold a\n * gitbeaker instance (HTTP server injecting shared clients, tests,\n * etc.) should instantiate `GitLabProvider` directly instead.\n */\nexport async function createGitLabProvider(\n opts: { auth: GitLabAuth, project: ProjectRef },\n): Promise<GitLabProvider> {\n const client = await createGitLabClient(opts.auth, opts.project.host)\n return new GitLabProvider(client, opts.project)\n}\n","import type { CommitAuthor } from '../../core/contracts/index.js'\n\n/**\n * A reference to a GitLab project.\n *\n * `projectId` accepts the numeric project ID or a URL-encoded path\n * (`namespace/project`). Gitbeaker URL-encodes string paths internally,\n * so either form is fine.\n *\n * `contentRoot` is the repo-relative directory prefix where Contentrain\n * content lives. For a flat content repo it stays `''`; for a monorepo\n * where Contentrain sits under `apps/web/.contentrain/` it holds that\n * prefix. All reader/writer paths are joined against it.\n *\n * `host` points at a self-hosted GitLab instance. Leave undefined to\n * use `https://gitlab.com` (gitbeaker's default).\n */\nexport interface ProjectRef {\n projectId: string | number\n contentRoot?: string\n host?: string\n}\n\n/**\n * Authentication options for the GitLab provider.\n *\n * - `pat` — personal access token with the `api` scope. Simplest for\n * self-hosted MCP or CI runners.\n * - `oauth` — OAuth2 token. Used when the runner is driven by a GitLab\n * OAuth flow.\n * - `job` — CI job token (`CI_JOB_TOKEN`). Scoped to the running\n * pipeline; useful for pipeline-driven content updates.\n */\nexport type GitLabAuth =\n | { type: 'pat', token: string }\n | { type: 'oauth', oauthToken: string }\n | { type: 'job', jobToken: string }\n\n/** Default author used when a call does not provide one. */\nexport const DEFAULT_GITLAB_AUTHOR: CommitAuthor = {\n name: 'Contentrain',\n email: 'ai@contentrain.io',\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAa,sBAA4C;CACvD,eAAe;CACf,YAAY;CACZ,aAAa;CACb,YAAY;CACZ,kBAAkB;CAClB,qBAAqB;CACrB,SAAS;CACV;;;;;;;;;;;;;;;;;;;;;;ACcD,eAAsB,kBACpB,QACA,SACA,OACiB;CACjB,MAAM,eAAe,MAAM,aAAa,QAAQ,SAAS,MAAM,OAAO;CAItE,MAAM,aAAa,MAAM,QAAQ;CAMjC,MAAM,yBAAyB,eAAe,MAAM,SAAS;CAI7D,MAAM,WAHa,MAAM,QAAQ,IAC/B,MAAM,QAAQ,KAAI,WAAU,cAAc,QAAQ,SAAS,wBAAwB,OAAO,CAAC,CAC5F,EAC0B,QAAQ,MAAyB,MAAM,KAAK;AAEvE,KAAI,QAAQ,WAAW,EAGrB,OAAM,IAAI,MAAM,0DAA0D;CAG5E,MAAM,UAAmC;EACvC,YAAY,MAAM,OAAO;EACzB,aAAa,MAAM,OAAO;EAC3B;AACD,KAAI,CAAC,aACH,SAAQ,cAAc;CAexB,MAAM,SAZW,MAAM,OAAO,QAAQ,OACpC,QAAQ,WACR,MAAM,QACN,MAAM,SACN,SACA,QACD;CAaD,MAAM,kBAAkB,eAAe,OAAO,WAAW,qBAAI,IAAI,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B,KAAK,QAAQ,KAAK,QAAQ;AAC5E,SAAOG,cAAgB,KAAK,QAAQ,KAAK,SAAS,QAAQ,SAAS;;CAErE,YAAY,QAAgB,MAAoC;AAC9D,SAAOC,YAAc,KAAK,QAAQ,KAAK,SAAS,QAAQ,KAAK;;CAE/D,MAAM,SAAS,QAAgB,MAAiC;EAC9D,MAAM,WAAW,QAAQ,MAAMJ,iBAAmB,KAAK,QAAQ,KAAK,QAAQ;AAC5E,SAAOK,SAAW,KAAK,QAAQ,KAAK,SAAS,QAAQ,SAAS;;CAEhE,mBAAoC;AAClC,SAAOL,iBAAmB,KAAK,QAAQ,KAAK,QAAQ;;;;;;;;;;;;;;;;;ACpExD,eAAsB,mBACpB,MACA,MACuB;CACvB,IAAI;AACJ,KAAI;AACF,GAAC,CAAE,QAAQ,cAAe,MAAM,OAAO;UAChC,OAAO;AACd,QAAM,IAAI,MACR,0IAEA,EAAE,OAAO,OAAO,CACjB;;CAGH,MAAM,SAAkC,OAAO,EAAE,MAAM,GAAG,EAAE;AAC5D,SAAQ,KAAK,MAAb;EACE,KAAK;AACH,UAAO,QAAQ,KAAK;AACpB;EACF,KAAK;AACH,UAAO,aAAa,KAAK;AACzB;EACF,KAAK;AACH,UAAO,WAAW,KAAK;AACvB;EACF,SAAS;GACP,MAAM,EAAE,SAAS;AACjB,SAAM,IAAI,MAAM,kCAAkC,KAAK,GAAG;;;AAI9D,QAAO,IAAI,WAAW,OAAO;;;;;;;;AAS/B,eAAsB,qBACpB,MACyB;AAEzB,QAAO,IAAI,eADI,MAAM,mBAAmB,KAAK,MAAM,KAAK,QAAQ,KAAK,EACnC,KAAK,QAAQ;;;;;ACtBjD,MAAa,wBAAsC;CACjD,MAAM;CACN,OAAO;CACR"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["listBranchesOp","getDefaultBranchOp","createBranchOp","deleteBranchOp","getBranchDiffOp","mergeBranchOp","isMergedOp"],"sources":["../../../src/providers/gitlab/capabilities.ts","../../../src/providers/gitlab/apply-plan.ts","../../../src/providers/gitlab/branch-ops.ts","../../../src/providers/gitlab/reader.ts","../../../src/providers/gitlab/provider.ts","../../../src/providers/gitlab/factory.ts","../../../src/providers/gitlab/types.ts"],"sourcesContent":["import type { ProviderCapabilities } from '../../core/contracts/index.js'\n\n/**\n * Capability set for GitLabProvider.\n *\n * GitLab over REST has no working tree, so local worktree features,\n * source-file access and AST scans are unavailable. Push, merge and\n * branch-protection detection all work over the API. GitLab enforces\n * merges through merge requests, so `pullRequestFallback` is `true` —\n * `mergeBranch` opens an MR and auto-accepts it to match GitHub's\n * `repos.merge` semantics while still leaving an audit trail.\n */\nexport const GITLAB_CAPABILITIES: ProviderCapabilities = {\n localWorktree: false,\n sourceRead: false,\n sourceWrite: false,\n pushRemote: true,\n branchProtection: true,\n pullRequestFallback: true,\n astScan: false,\n}\n","import { CONTENTRAIN_BRANCH } from '@contentrain/types'\nimport type { ApplyPlanInput, Commit, FileChange } from '../../core/contracts/index.js'\nimport { isNotFoundError, resolveRepoPath } from '../shared/index.js'\nimport type { GitLabClient } from './client.js'\nimport type { ProjectRef } from './types.js'\n\ntype CommitActionType = 'create' | 'update' | 'delete'\n\ninterface CommitAction {\n action: CommitActionType\n filePath: string\n content?: string\n encoding?: 'text' | 'base64'\n}\n\n/**\n * Apply a plan to a GitLab repository as a single atomic commit via the\n * Commits API. High-level flow:\n *\n * 1. Check whether the target branch exists. If it does not, GitLab's\n * `startBranch` option forks a new branch from `input.base` (or the\n * project's default branch) as part of the same commit.\n * 2. For each `FileChange`, figure out the right GitLab action verb\n * (`create` vs `update` vs `delete`) by probing the path against the\n * resolved ref. GitLab validates this server-side and returns a 400\n * for mismatches — we avoid the round trip by getting it right up\n * front.\n * 3. POST `/repository/commits` once with the full action set. No\n * working tree, no multi-call tree-assembly dance — GitLab exposes\n * a richer primitive than the GitHub Git Data API for this case.\n *\n * The commit is durable as soon as the call returns; GitLab's ref\n * update happens inside the same request.\n */\nexport async function applyPlanToGitLab(\n client: GitLabClient,\n project: ProjectRef,\n input: ApplyPlanInput,\n): Promise<Commit> {\n const branchExists = await branchHasRef(client, project, input.branch)\n // Invariant: fork from the Contentrain content-tracking branch, not\n // the repo's default branch. See ApplyPlanInput.base docstring in\n // @contentrain/types.\n const baseBranch = input.base ?? CONTENTRAIN_BRANCH\n\n // Actions are computed against the HEAD of the feature branch when it\n // exists, otherwise against the fork point (baseBranch). GitLab\n // treats `create` / `update` / `delete` as a strict check against the\n // path's existence at that ref.\n const refForActionResolution = branchExists ? input.branch : baseBranch\n const rawActions = await Promise.all(\n input.changes.map(change => resolveAction(client, project, refForActionResolution, change)),\n )\n const actions = rawActions.filter((a): a is CommitAction => a !== null)\n\n if (actions.length === 0) {\n // Nothing to apply. Callers don't generally build empty plans, but\n // if they do we short-circuit before touching the API.\n throw new Error('applyPlanToGitLab: plan contained no applicable actions')\n }\n\n const options: Record<string, unknown> = {\n authorName: input.author.name,\n authorEmail: input.author.email,\n }\n if (!branchExists) {\n options.startBranch = baseBranch\n }\n\n const response = await client.Commits.create(\n project.projectId,\n input.branch,\n input.message,\n actions,\n options,\n )\n\n // Gitbeaker's generic-heavy response type widens string fields to\n // `string | Camelize<…>` — at runtime they are always strings under\n // the default (non-camelize) response mode we use. Cast narrows the\n // shape we actually touch.\n const commit = response as {\n id: string\n message?: string\n author_name?: string\n author_email?: string\n created_at?: string\n }\n const commitTimestamp = toIsoTimestamp(commit.created_at) ?? new Date().toISOString()\n return {\n sha: commit.id,\n message: commit.message ?? input.message,\n author: {\n name: commit.author_name ?? input.author.name,\n email: commit.author_email ?? input.author.email,\n },\n timestamp: commitTimestamp,\n }\n}\n\nasync function resolveAction(\n client: GitLabClient,\n project: ProjectRef,\n ref: string,\n change: FileChange,\n): Promise<CommitAction | null> {\n const filePath = resolveRepoPath(project.contentRoot, change.path)\n const exists = await fileExistsAtRef(client, project, filePath, ref)\n\n if (change.content === null) {\n // Filter out deletes against non-existent files — GitLab returns\n // 400 otherwise. The plan author asked us to \"make this file not\n // exist\", which is already satisfied.\n if (!exists) return null\n return { action: 'delete', filePath }\n }\n\n return {\n action: exists ? 'update' : 'create',\n filePath,\n content: change.content,\n encoding: 'text',\n }\n}\n\nasync function branchHasRef(\n client: GitLabClient,\n project: ProjectRef,\n branch: string,\n): Promise<boolean> {\n try {\n await client.Branches.show(project.projectId, branch)\n return true\n } catch (error) {\n if (isNotFoundError(error)) return false\n throw error\n }\n}\n\nasync function fileExistsAtRef(\n client: GitLabClient,\n project: ProjectRef,\n filePath: string,\n ref: string,\n): Promise<boolean> {\n try {\n await client.RepositoryFiles.show(project.projectId, filePath, ref)\n return true\n } catch (error) {\n if (isNotFoundError(error)) return false\n throw error\n }\n}\n\n\nfunction toIsoTimestamp(raw: unknown): string | null {\n if (typeof raw !== 'string') return null\n const date = new Date(raw)\n if (Number.isNaN(date.getTime())) return null\n return date.toISOString()\n}\n\n","import type { Branch, FileDiff, MergeResult } from '../../core/contracts/index.js'\nimport type { GitLabClient } from './client.js'\nimport type { ProjectRef } from './types.js'\n\n/**\n * Branch / merge / diff helpers backed by the GitLab REST API.\n *\n * Pure functions so they can be composed into `GitLabProvider` or used\n * standalone. 404s collapse to empty-ish results where that matches\n * the `RepoProvider` contract (missing branch prefix → `[]`).\n *\n * Merge semantics: GitLab does not expose a direct branch-to-branch\n * merge endpoint. Every merge flows through a merge request, so\n * `mergeBranch` opens an MR and immediately accepts it. The resulting\n * `MergeResult` mirrors GitHub's `repos.merge` return shape — callers\n * see the same `{ merged, sha, pullRequestUrl }` envelope either way,\n * with the MR URL available for audit.\n */\n\nexport async function getDefaultBranch(\n client: GitLabClient,\n project: ProjectRef,\n): Promise<string> {\n const p = await client.Projects.show(project.projectId) as { default_branch?: string }\n return p.default_branch ?? 'main'\n}\n\nexport async function listBranches(\n client: GitLabClient,\n project: ProjectRef,\n prefix?: string,\n): Promise<Branch[]> {\n // Gitbeaker's `all` supports a `search` string (substring match). For\n // Contentrain's `cr/*` naming the substring case is equivalent to a\n // prefix because the slug never appears anywhere except at the start.\n // Server-side filter + client-side prefix enforcement keeps us\n // correct even if the substring coincidence breaks someday.\n const options: Record<string, unknown> = {\n perPage: 100,\n maxPages: 10,\n }\n if (prefix) options.search = prefix\n\n const rawBranches = await client.Branches.all(project.projectId, options)\n const branches = Array.isArray(rawBranches) ? rawBranches : []\n\n return branches\n .filter((b: { name: string }) => !prefix || b.name.startsWith(prefix))\n .map((b: { name: string, commit: { id: string }, protected?: boolean }) => ({\n name: b.name,\n sha: b.commit.id,\n protected: b.protected ?? false,\n }))\n}\n\nexport async function createBranch(\n client: GitLabClient,\n project: ProjectRef,\n name: string,\n fromRef: string,\n): Promise<void> {\n await client.Branches.create(project.projectId, name, fromRef)\n}\n\nexport async function deleteBranch(\n client: GitLabClient,\n project: ProjectRef,\n name: string,\n): Promise<void> {\n await client.Branches.remove(project.projectId, name)\n}\n\nexport async function getBranchDiff(\n client: GitLabClient,\n project: ProjectRef,\n branch: string,\n base: string,\n): Promise<FileDiff[]> {\n const response = await client.Repositories.compare(\n project.projectId,\n base,\n branch,\n { straight: false },\n )\n const diffs = Array.isArray(response.diffs) ? response.diffs : []\n return diffs.map((d: { new_path: string, old_path: string, new_file?: boolean, deleted_file?: boolean }) => ({\n path: d.new_file ? d.new_path : d.old_path,\n status: d.deleted_file ? 'removed' : d.new_file ? 'added' : 'modified',\n before: null,\n after: null,\n }))\n}\n\nexport async function mergeBranch(\n client: GitLabClient,\n project: ProjectRef,\n branch: string,\n into: string,\n opts?: { removeSourceBranch?: boolean },\n): Promise<MergeResult> {\n // 1. Open MR — GitLab rejects create when source === target or when\n // an MR is already open for this pair. Let the error propagate in\n // those cases; the caller retries or surfaces the message.\n const mr = await client.MergeRequests.create(\n project.projectId,\n branch,\n into,\n `[contentrain] merge ${branch} → ${into}`,\n { removeSourceBranch: false },\n )\n\n // 2. Accept the MR immediately. `shouldRemoveSourceBranch: false` keeps\n // GitLab's async server-side deletion out of the accept call — the\n // explicit cleanup below owns it, so the outcome is deterministic and\n // reported via `MergeResult.remote`.\n const accepted = await client.MergeRequests.accept(\n project.projectId,\n (mr as { iid: number }).iid,\n { shouldRemoveSourceBranch: false, squash: false },\n )\n\n const mergeSha = (accepted as { merge_commit_sha?: string | null, sha?: string | null }).merge_commit_sha\n ?? (accepted as { sha?: string | null }).sha\n ?? null\n const webUrl = (mr as { web_url?: string }).web_url ?? null\n const merged = mergeSha !== null\n\n // 3. Best-effort source-branch cleanup so merged cr/* branches don't\n // pile up on the remote. Opt out per call with\n // `removeSourceBranch: false` (e.g. a driver that owns cleanup\n // separately). Never throws — the merge itself already succeeded.\n let remote: MergeResult['remote']\n if (merged && opts?.removeSourceBranch !== false) {\n try {\n await deleteBranch(client, project, branch)\n remote = { deleted: true }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n remote = /404|not found/i.test(message)\n ? { deleted: false, skipped: 'not-found' }\n : { deleted: false, warning: `Could not delete \"${branch}\": ${message}` }\n }\n }\n\n return { merged, sha: mergeSha, pullRequestUrl: webUrl, ...(remote ? { remote } : {}) }\n}\n\nexport async function isMerged(\n client: GitLabClient,\n project: ProjectRef,\n branch: string,\n into: string,\n): Promise<boolean> {\n // compare(from=into, to=branch) — commits list is empty when branch\n // is fully contained in into (i.e. already merged).\n const response = await client.Repositories.compare(\n project.projectId,\n into,\n branch,\n { straight: false },\n )\n const commits = Array.isArray(response.commits) ? response.commits : []\n return commits.length === 0\n}\n","import type { RepoReader } from '../../core/contracts/index.js'\nimport { isNotFoundError, resolveRepoPath } from '../shared/index.js'\nimport type { GitLabClient } from './client.js'\nimport type { ProjectRef } from './types.js'\n\n/**\n * GitLabReader — `RepoReader` backed by the GitLab REST API.\n *\n * File reads go through `RepositoryFiles.showRaw`, which returns the\n * file content as UTF-8 text (or a `Blob` on browser/edge runtimes we\n * decode with `.text()`). Directory listings go through\n * `Repositories.allRepositoryTrees`. `fileExists` tries the file\n * endpoint first and falls back to a tree listing so directories\n * resolve to `true` as well — matching LocalReader / GitHubReader.\n *\n * `ref` is forwarded verbatim and may be a branch name, tag name or\n * commit SHA. Callers should always pass the explicit `contentrain`\n * tracking branch; GitLab's default resolution is the project's\n * default branch, which is usually wrong for Contentrain flows.\n */\nexport class GitLabReader implements RepoReader {\n constructor(\n private readonly client: GitLabClient,\n private readonly project: ProjectRef,\n ) {}\n\n async readFile(path: string, ref?: string): Promise<string> {\n const repoPath = resolveRepoPath(this.project.contentRoot, path)\n const resolvedRef = ref ?? await this.resolveDefaultRef()\n const raw = await this.client.RepositoryFiles.showRaw(\n this.project.projectId,\n repoPath,\n resolvedRef,\n )\n if (typeof raw === 'string') return raw\n // Browser / edge runtimes return a Blob; decode as UTF-8.\n return (raw as Blob).text()\n }\n\n async listDirectory(path: string, ref?: string): Promise<string[]> {\n const repoPath = resolveRepoPath(this.project.contentRoot, path)\n const resolvedRef = ref ?? await this.resolveDefaultRef()\n try {\n const entries = await this.client.Repositories.allRepositoryTrees(\n this.project.projectId,\n {\n path: repoPath,\n ref: resolvedRef,\n perPage: 100,\n recursive: false,\n },\n )\n return Array.isArray(entries) ? entries.map(e => e.name) : []\n } catch (error) {\n if (isNotFoundError(error)) return []\n throw error\n }\n }\n\n async fileExists(path: string, ref?: string): Promise<boolean> {\n const repoPath = resolveRepoPath(this.project.contentRoot, path)\n const resolvedRef = ref ?? await this.resolveDefaultRef()\n\n // 1. Try as a file — cheap and most common case for Contentrain.\n try {\n await this.client.RepositoryFiles.show(\n this.project.projectId,\n repoPath,\n resolvedRef,\n )\n return true\n } catch (error) {\n if (!isNotFoundError(error)) throw error\n }\n\n // 2. Fall back to a tree listing — directories and empty dirs show\n // up here. Any non-404 result means the path resolves.\n try {\n const entries = await this.client.Repositories.allRepositoryTrees(\n this.project.projectId,\n { path: repoPath, ref: resolvedRef, perPage: 1 },\n )\n return Array.isArray(entries) && entries.length > 0\n } catch (error) {\n if (isNotFoundError(error)) return false\n throw error\n }\n }\n\n private async resolveDefaultRef(): Promise<string> {\n const project = await this.client.Projects.show(this.project.projectId) as { default_branch?: string }\n return project.default_branch ?? 'main'\n }\n}\n\n","import type {\n ApplyPlanInput,\n Branch,\n Commit,\n FileDiff,\n MergeResult,\n ProviderCapabilities,\n RepoProvider,\n} from '../../core/contracts/index.js'\nimport { applyPlanToGitLab } from './apply-plan.js'\nimport {\n createBranch as createBranchOp,\n deleteBranch as deleteBranchOp,\n getBranchDiff as getBranchDiffOp,\n getDefaultBranch as getDefaultBranchOp,\n isMerged as isMergedOp,\n listBranches as listBranchesOp,\n mergeBranch as mergeBranchOp,\n} from './branch-ops.js'\nimport { GITLAB_CAPABILITIES } from './capabilities.js'\nimport type { GitLabClient } from './client.js'\nimport { GitLabReader } from './reader.js'\nimport type { ProjectRef } from './types.js'\n\n/**\n * GitLabProvider — `RepoProvider` backed by the gitbeaker-driven GitLab\n * REST API.\n *\n * Transport-agnostic: the provider only talks to a `GitLabClient`\n * (a `@gitbeaker/rest` `Gitlab` instance). `createGitLabProvider` in\n * `factory.ts` wraps the dynamic import so consumers never touch\n * `@gitbeaker/rest` directly unless they want to.\n *\n * Capability gaps versus `GitHubProvider`: none — both providers\n * expose the same set. GitLab's merge flow routes through an MR under\n * the hood, but `mergeBranch` presents the same `MergeResult` shape.\n */\nexport class GitLabProvider implements RepoProvider {\n readonly capabilities: ProviderCapabilities = GITLAB_CAPABILITIES\n private readonly reader: GitLabReader\n\n constructor(\n private readonly client: GitLabClient,\n public readonly project: ProjectRef,\n ) {\n this.reader = new GitLabReader(client, project)\n }\n\n readFile(path: string, ref?: string): Promise<string> {\n return this.reader.readFile(path, ref)\n }\n listDirectory(path: string, ref?: string): Promise<string[]> {\n return this.reader.listDirectory(path, ref)\n }\n fileExists(path: string, ref?: string): Promise<boolean> {\n return this.reader.fileExists(path, ref)\n }\n\n applyPlan(input: ApplyPlanInput): Promise<Commit> {\n return applyPlanToGitLab(this.client, this.project, input)\n }\n\n listBranches(prefix?: string): Promise<Branch[]> {\n return listBranchesOp(this.client, this.project, prefix)\n }\n async createBranch(name: string, fromRef?: string): Promise<void> {\n const resolved = fromRef ?? await getDefaultBranchOp(this.client, this.project)\n await createBranchOp(this.client, this.project, name, resolved)\n }\n deleteBranch(name: string): Promise<void> {\n return deleteBranchOp(this.client, this.project, name)\n }\n async getBranchDiff(branch: string, base?: string): Promise<FileDiff[]> {\n const resolved = base ?? await getDefaultBranchOp(this.client, this.project)\n return getBranchDiffOp(this.client, this.project, branch, resolved)\n }\n mergeBranch(branch: string, into: string, opts?: { removeSourceBranch?: boolean }): Promise<MergeResult> {\n return mergeBranchOp(this.client, this.project, branch, into, opts)\n }\n async isMerged(branch: string, into?: string): Promise<boolean> {\n const resolved = into ?? await getDefaultBranchOp(this.client, this.project)\n return isMergedOp(this.client, this.project, branch, resolved)\n }\n getDefaultBranch(): Promise<string> {\n return getDefaultBranchOp(this.client, this.project)\n }\n}\n","import type { GitLabClient } from './client.js'\nimport { GitLabProvider } from './provider.js'\nimport type { GitLabAuth, ProjectRef } from './types.js'\n\n/**\n * Create a gitbeaker-backed `GitLabClient` from an auth configuration.\n *\n * The `@gitbeaker/rest` module is imported dynamically so it stays a\n * pure optional peer dependency — self-hosted MCP on stdio runs fine\n * without it. If the module is not installed, the import throws with\n * a helpful hint pointing the operator at the peer dependency.\n *\n * Supported auth types: `pat`, `oauth`, `job`. All three are thin\n * wrappers over gitbeaker's `token`, `oauthToken`, and `jobToken`\n * constructor options.\n */\nexport async function createGitLabClient(\n auth: GitLabAuth,\n host?: string,\n): Promise<GitLabClient> {\n let GitlabCtor: typeof import('@gitbeaker/rest').Gitlab\n try {\n ({ Gitlab: GitlabCtor } = await import('@gitbeaker/rest'))\n } catch (error) {\n throw new Error(\n '@gitbeaker/rest is required for the GitLabProvider but could not be loaded. '\n + 'Install it as a peer dependency: pnpm add @gitbeaker/rest.',\n { cause: error },\n )\n }\n\n const config: Record<string, unknown> = host ? { host } : {}\n switch (auth.type) {\n case 'pat':\n config.token = auth.token\n break\n case 'oauth':\n config.oauthToken = auth.oauthToken\n break\n case 'job':\n config.jobToken = auth.jobToken\n break\n default: {\n const { type } = auth as { type: string }\n throw new Error(`Unsupported GitLab auth type: \"${type}\"`)\n }\n }\n\n return new GitlabCtor(config) as GitLabClient\n}\n\n/**\n * Factory for the full provider — instantiates a gitbeaker client and\n * wraps it in a `GitLabProvider`. Consumers who already hold a\n * gitbeaker instance (HTTP server injecting shared clients, tests,\n * etc.) should instantiate `GitLabProvider` directly instead.\n */\nexport async function createGitLabProvider(\n opts: { auth: GitLabAuth, project: ProjectRef },\n): Promise<GitLabProvider> {\n const client = await createGitLabClient(opts.auth, opts.project.host)\n return new GitLabProvider(client, opts.project)\n}\n","import type { CommitAuthor } from '../../core/contracts/index.js'\n\n/**\n * A reference to a GitLab project.\n *\n * `projectId` accepts the numeric project ID or a URL-encoded path\n * (`namespace/project`). Gitbeaker URL-encodes string paths internally,\n * so either form is fine.\n *\n * `contentRoot` is the repo-relative directory prefix where Contentrain\n * content lives. For a flat content repo it stays `''`; for a monorepo\n * where Contentrain sits under `apps/web/.contentrain/` it holds that\n * prefix. All reader/writer paths are joined against it.\n *\n * `host` points at a self-hosted GitLab instance. Leave undefined to\n * use `https://gitlab.com` (gitbeaker's default).\n */\nexport interface ProjectRef {\n projectId: string | number\n contentRoot?: string\n host?: string\n}\n\n/**\n * Authentication options for the GitLab provider.\n *\n * - `pat` — personal access token with the `api` scope. Simplest for\n * self-hosted MCP or CI runners.\n * - `oauth` — OAuth2 token. Used when the runner is driven by a GitLab\n * OAuth flow.\n * - `job` — CI job token (`CI_JOB_TOKEN`). Scoped to the running\n * pipeline; useful for pipeline-driven content updates.\n */\nexport type GitLabAuth =\n | { type: 'pat', token: string }\n | { type: 'oauth', oauthToken: string }\n | { type: 'job', jobToken: string }\n\n/** Default author used when a call does not provide one. */\nexport const DEFAULT_GITLAB_AUTHOR: CommitAuthor = {\n name: 'Contentrain',\n email: 'ai@contentrain.io',\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAa,sBAA4C;CACvD,eAAe;CACf,YAAY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