@phren/cli 0.3.37 → 0.3.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge/account-failover.d.ts +4 -0
- package/dist/bridge/account-failover.js +12 -4
- package/dist/bridge/account-usage.d.ts +5 -2
- package/dist/bridge/account-usage.js +36 -6
- package/dist/bridge/agent-hooks.js +2 -0
- package/dist/bridge/changes.d.ts +5 -0
- package/dist/bridge/changes.js +4 -0
- package/dist/bridge/claude-accounts.d.ts +15 -4
- package/dist/bridge/claude-accounts.js +31 -16
- package/dist/bridge/claude-credits.d.ts +43 -0
- package/dist/bridge/claude-credits.js +236 -0
- package/dist/bridge/claude-question-dialog.js +6 -2
- package/dist/bridge/command.js +64 -3
- package/dist/bridge/device-enroll.d.ts +34 -0
- package/dist/bridge/device-enroll.js +57 -0
- package/dist/bridge/dispatch-command.d.ts +2 -0
- package/dist/bridge/dispatch-command.js +25 -1
- package/dist/bridge/dispatch-returns.d.ts +7 -0
- package/dist/bridge/dispatch-returns.js +56 -6
- package/dist/bridge/dispatch.d.ts +52 -0
- package/dist/bridge/dispatch.js +14 -0
- package/dist/bridge/file-range.d.ts +3 -0
- package/dist/bridge/file-range.js +5 -4
- package/dist/bridge/file-search.d.ts +37 -0
- package/dist/bridge/file-search.js +87 -0
- package/dist/bridge/file-write.d.ts +6 -0
- package/dist/bridge/file-write.js +120 -0
- package/dist/bridge/git-host-auth.d.ts +31 -0
- package/dist/bridge/git-host-auth.js +110 -0
- package/dist/bridge/git-host-gitboy.d.ts +46 -0
- package/dist/bridge/git-host-gitboy.js +296 -0
- package/dist/bridge/git-host-gitlab.d.ts +25 -0
- package/dist/bridge/git-host-gitlab.js +229 -0
- package/dist/bridge/git-host-http.d.ts +33 -0
- package/dist/bridge/git-host-http.js +70 -0
- package/dist/bridge/git-hosts.d.ts +92 -0
- package/dist/bridge/git-hosts.js +244 -0
- package/dist/bridge/git-publish.d.ts +15 -5
- package/dist/bridge/git-publish.js +69 -21
- package/dist/bridge/git-review.d.ts +23 -0
- package/dist/bridge/git-review.js +170 -0
- package/dist/bridge/git-sync.d.ts +14 -0
- package/dist/bridge/git-sync.js +143 -0
- package/dist/bridge/git.d.ts +20 -7
- package/dist/bridge/git.js +87 -68
- package/dist/bridge/gitboy-contract.d.ts +32 -0
- package/dist/bridge/gitboy-contract.js +46 -0
- package/dist/bridge/hand-off.d.ts +52 -2
- package/dist/bridge/hand-off.js +77 -24
- package/dist/bridge/health.d.ts +1 -1
- package/dist/bridge/health.js +5 -3
- package/dist/bridge/install.d.ts +14 -0
- package/dist/bridge/install.js +40 -1
- package/dist/bridge/memory-store.d.ts +8 -0
- package/dist/bridge/memory-store.js +80 -2
- package/dist/bridge/pair.d.ts +6 -1
- package/dist/bridge/pair.js +74 -2
- package/dist/bridge/project-memory.d.ts +94 -0
- package/dist/bridge/project-memory.js +235 -0
- package/dist/bridge/push.d.ts +15 -0
- package/dist/bridge/push.js +39 -0
- package/dist/bridge/scoped-gateway.d.ts +29 -0
- package/dist/bridge/scoped-gateway.js +239 -0
- package/dist/bridge/server-launch.d.ts +12 -0
- package/dist/bridge/server-launch.js +17 -10
- package/dist/bridge/server-pane-routes.js +54 -3
- package/dist/bridge/server-routes.d.ts +12 -0
- package/dist/bridge/server-routes.js +59 -4
- package/dist/bridge/server.js +44 -5
- package/dist/bridge/session-move.d.ts +288 -0
- package/dist/bridge/session-move.js +600 -0
- package/dist/bridge/subscription.d.ts +15 -0
- package/dist/bridge/subscription.js +23 -0
- package/dist/bridge/transport.js +21 -1
- package/dist/bridge/usage.d.ts +20 -3
- package/dist/bridge/usage.js +61 -11
- package/dist/bridge-hook.mjs +12751 -3207
- package/dist/cli-registry.js +10 -4
- package/dist/computers/command.js +3 -1
- package/dist/computers/read.d.ts +3 -0
- package/dist/computers/read.js +6 -0
- package/dist/content/summarize.d.ts +21 -0
- package/dist/content/summarize.js +56 -18
- package/dist/modules/registry.js +12 -12
- package/dist/project-config.d.ts +12 -0
- package/dist/project-config.js +29 -0
- package/dist/shared/retrieval.d.ts +1 -0
- package/dist/shared/retrieval.js +1 -1
- package/dist/sync/conflict-resolve.js +5 -6
- package/dist/tools/dispatch.js +18 -1
- package/dist/tools/finding.d.ts +25 -0
- package/dist/tools/finding.js +2 -1
- package/package.json +57 -1
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
import { resolveHostToken } from "./git-host-auth.js";
|
|
2
|
+
import { fillFromCommits } from "./git-host-gitlab.js";
|
|
3
|
+
import { apiRoot, HostApiError, hostJson, safeLink } from "./git-host-http.js";
|
|
4
|
+
import { git } from "./projects.js";
|
|
5
|
+
/** gitboy, the self-hosted forge, over its REST API (/api/v1). gitboy names a
|
|
6
|
+
* pull request by `index`, and an older gitboy has no draft state, no aggregate review decision
|
|
7
|
+
* and no web links in its answers, so this provider derives them: web pages
|
|
8
|
+
* are `<origin>/<owner>/<repo>/pulls/<n>` and `/pipelines/<iid>?job=<id>`, a
|
|
9
|
+
* review decision counts approvals on the head commit, and a newer gitboy
|
|
10
|
+
* that sends `html_url`, `draft` or `review_decision` is taken at its word.
|
|
11
|
+
* The token is GITBOY_TOKEN (for the domain GITBOY_HOST names) or the Hook's stored one, a gbp_ personal access
|
|
12
|
+
* token with read:user and read:repo (write:repo to open or merge); gitboy's
|
|
13
|
+
* "Phren Hook" token preset grants exactly those. A gitboy with head_branch and
|
|
14
|
+
* sha filters gets them; an older one ignores them and the client filters below
|
|
15
|
+
* still pick the right rows. */
|
|
16
|
+
export const PULL_TERMS = { short: "PR", long: "pull request", ref: "#" };
|
|
17
|
+
const ORDER = { failing: 0, pending: 1, passing: 2, skipped: 3, neutral: 4 };
|
|
18
|
+
/** A gitboy job or pipeline status as one state word. */
|
|
19
|
+
export function gitboyState(status, allowFailure = false) {
|
|
20
|
+
switch (String(status ?? "").toLowerCase()) {
|
|
21
|
+
case "success": return "passing";
|
|
22
|
+
case "failed":
|
|
23
|
+
case "failure":
|
|
24
|
+
case "error": return allowFailure ? "neutral" : "failing";
|
|
25
|
+
case "canceled":
|
|
26
|
+
case "cancelled": return allowFailure ? "neutral" : "failing";
|
|
27
|
+
case "skipped": return "skipped";
|
|
28
|
+
default: return "pending"; // created, blocked, queued, claimed, running, pending
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function obj(value) {
|
|
32
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
33
|
+
}
|
|
34
|
+
function rows(value) {
|
|
35
|
+
const list = Array.isArray(value) ? value : Array.isArray(obj(value).items) ? obj(value).items : [];
|
|
36
|
+
return list.map(obj);
|
|
37
|
+
}
|
|
38
|
+
function stateOf(pull) {
|
|
39
|
+
if (pull.merged_at)
|
|
40
|
+
return "MERGED";
|
|
41
|
+
return String(pull.state ?? "").toLowerCase() === "open" ? "OPEN" : "CLOSED";
|
|
42
|
+
}
|
|
43
|
+
const SIGN_IN = (domain) => `Phren has no gitboy token for ${domain}. Connect it from the desktop's Changes pane, or run phren bridge git-host set ${domain} gitboy on this computer with a personal access token that has read:user and read:repo (write:repo to open and merge); gitboy's Settings → Access tokens has a "Phren Hook" preset.`;
|
|
44
|
+
async function context(root, host) {
|
|
45
|
+
const repo = host.webUrl?.replace(/^https?:\/\/[^/]+\//, "") ?? "";
|
|
46
|
+
if (!host.domain || repo.split("/").length !== 2)
|
|
47
|
+
return { available: false, reason: "unknown-host", message: "This repository has no gitboy remote of the form owner/repo.", pulls: [], current: null };
|
|
48
|
+
const token = await resolveHostToken("gitboy", host.domain);
|
|
49
|
+
if (!token)
|
|
50
|
+
return { available: false, reason: "auth", message: SIGN_IN(host.domain), pulls: [], current: null };
|
|
51
|
+
const api = await apiRoot(root, host.domain, `https://${host.domain}/api/v1`);
|
|
52
|
+
return { api, web: api.replace(/\/api\/v1$/, ""), repo, token: token.token, domain: host.domain, account: { source: token.source, ...(token.user ? { user: token.user } : {}) } };
|
|
53
|
+
}
|
|
54
|
+
function call(ctx, path, init = {}) {
|
|
55
|
+
return hostJson(`${ctx.api}/repos/${ctx.repo}${path}`, { token: ctx.token, scheme: "bearer", ...init });
|
|
56
|
+
}
|
|
57
|
+
/** Whether a pull request's head lives in this repository rather than a fork
|
|
58
|
+
* with a branch of the same name. gitboy names it in `head_repository`
|
|
59
|
+
* (owner_username, name); a row without one is taken as this repository's. */
|
|
60
|
+
export function sameRepository(ctx, pull) {
|
|
61
|
+
const head = obj(pull.head_repository);
|
|
62
|
+
if (typeof head.owner_username !== "string" || typeof head.name !== "string")
|
|
63
|
+
return true;
|
|
64
|
+
return `${head.owner_username}/${head.name}`.toLowerCase() === ctx.repo.toLowerCase();
|
|
65
|
+
}
|
|
66
|
+
/** Whether the branch was pushed: its remote-tracking ref, read locally so an
|
|
67
|
+
* error path never waits on the network or a credential prompt. */
|
|
68
|
+
async function remoteHasBranch(root, remote, branch) {
|
|
69
|
+
return git(root, "show-ref", "--verify", "--quiet", `refs/remotes/${remote}/${branch}`).then(() => true, () => false);
|
|
70
|
+
}
|
|
71
|
+
/** gitboy's reasons it will not merge: a 409's `details`, else the message. */
|
|
72
|
+
export function refusalReasons(error) {
|
|
73
|
+
const body = obj(error.body);
|
|
74
|
+
const details = Array.isArray(body.details) ? body.details.map(item => String(item).slice(0, 300)).filter(Boolean).slice(0, 10) : [];
|
|
75
|
+
const message = error.message.replace(/^.*? answered \d+:? ?/, "");
|
|
76
|
+
if (details.length)
|
|
77
|
+
return `${message && message !== "Pull request cannot be merged" ? `${message}: ` : ""}${details.join("; ")}`;
|
|
78
|
+
return message || "gitboy says it can't be merged yet.";
|
|
79
|
+
}
|
|
80
|
+
function pullUrl(ctx, pull) {
|
|
81
|
+
return safeLink(pull.html_url) ?? `${ctx.web}/${ctx.repo}/pulls/${pull.index ?? pull.number}`;
|
|
82
|
+
}
|
|
83
|
+
function listed(ctx, pull) {
|
|
84
|
+
const number = typeof pull.index === "number" ? pull.index : pull.number;
|
|
85
|
+
return { number, title: String(pull.title ?? ""), head: String(pull.head_branch ?? ""), base: String(pull.base_branch ?? ""),
|
|
86
|
+
author: String(pull.author_username ?? ""), url: pullUrl(ctx, pull), draft: pull.draft === true, state: stateOf(pull),
|
|
87
|
+
updated: String(pull.updated_at ?? "") };
|
|
88
|
+
}
|
|
89
|
+
/** GitHub's reviewDecision from gitboy's reviews: each reviewer's latest
|
|
90
|
+
* verdict on the head commit, the author's own left out. */
|
|
91
|
+
export function gitboyReviewDecision(pull) {
|
|
92
|
+
if (typeof pull.review_decision === "string" && pull.review_decision)
|
|
93
|
+
return pull.review_decision.toUpperCase();
|
|
94
|
+
const head = String(pull.head_sha ?? "");
|
|
95
|
+
const latest = new Map();
|
|
96
|
+
for (const review of rows(pull.reviews).sort((a, b) => String(a.created_at ?? "").localeCompare(String(b.created_at ?? "")))) {
|
|
97
|
+
const who = String(review.reviewer_username ?? review.reviewer_id ?? "");
|
|
98
|
+
if (!who || who === pull.author_username)
|
|
99
|
+
continue;
|
|
100
|
+
const state = String(review.state ?? "");
|
|
101
|
+
if (state === "changes_requested")
|
|
102
|
+
latest.set(who, state);
|
|
103
|
+
else if (state === "approved" && (!head || review.commit_sha === head))
|
|
104
|
+
latest.set(who, state);
|
|
105
|
+
}
|
|
106
|
+
const verdicts = [...latest.values()];
|
|
107
|
+
if (verdicts.includes("changes_requested"))
|
|
108
|
+
return "CHANGES_REQUESTED";
|
|
109
|
+
const blockers = Array.isArray(pull.merge_blockers) ? pull.merge_blockers.map(String) : [];
|
|
110
|
+
if (blockers.some(text => /approval/i.test(text)))
|
|
111
|
+
return "REVIEW_REQUIRED";
|
|
112
|
+
return verdicts.includes("approved") ? "APPROVED" : undefined;
|
|
113
|
+
}
|
|
114
|
+
/** gitboy's mergeability and blockers in GitHub's mergeStateStatus words. */
|
|
115
|
+
export function gitboyMergeState(pull) {
|
|
116
|
+
const blockers = (Array.isArray(pull.merge_blockers) ? pull.merge_blockers : []).map(text => String(text).slice(0, 300)).slice(0, 20);
|
|
117
|
+
const status = String(pull.status ?? "");
|
|
118
|
+
if (stateOf(pull) !== "OPEN")
|
|
119
|
+
return {};
|
|
120
|
+
if (status === "conflict")
|
|
121
|
+
return { mergeState: "DIRTY", mergeDetail: "Has merge conflicts", ...(blockers.length ? { blockers } : {}) };
|
|
122
|
+
if (status === "checking" || status === "")
|
|
123
|
+
return { mergeState: "UNKNOWN", mergeDetail: "Checking mergeability", ...(blockers.length ? { blockers } : {}) };
|
|
124
|
+
if (status === "empty" || status === "ancestor")
|
|
125
|
+
return { mergeState: "UNKNOWN", mergeDetail: "No changes to merge" };
|
|
126
|
+
if (status === "error")
|
|
127
|
+
return { mergeState: "UNKNOWN", mergeDetail: "gitboy could not check mergeability" };
|
|
128
|
+
if (blockers.length)
|
|
129
|
+
return { mergeState: "BLOCKED", mergeDetail: blockers[0], blockers };
|
|
130
|
+
return { mergeState: "CLEAN", mergeDetail: "Ready to merge" };
|
|
131
|
+
}
|
|
132
|
+
/** The head commit's pipeline jobs, newest attempt of each; failing first. */
|
|
133
|
+
async function jobsFor(ctx, pull) {
|
|
134
|
+
const sha = String(pull.head_sha ?? "");
|
|
135
|
+
const branch = String(pull.head_branch ?? "");
|
|
136
|
+
if (!sha || !branch)
|
|
137
|
+
return { runs: [] };
|
|
138
|
+
const { json } = await call(ctx, `/pipelines?branch=${encodeURIComponent(branch)}&sha=${encodeURIComponent(sha)}&limit=20`).catch(() => ({ json: [] }));
|
|
139
|
+
const pipeline = rows(json).filter(p => p.sha === sha).sort((a, b) => Number(b.iid ?? 0) - Number(a.iid ?? 0))[0];
|
|
140
|
+
if (!pipeline || pipeline.iid === undefined)
|
|
141
|
+
return { runs: [] };
|
|
142
|
+
const { json: detail } = await call(ctx, `/pipelines/${pipeline.iid}`).catch(() => ({ json: {} }));
|
|
143
|
+
const newest = new Map();
|
|
144
|
+
for (const job of rows(obj(detail).jobs)) {
|
|
145
|
+
const name = String(job.name ?? "Job");
|
|
146
|
+
const seen = newest.get(name);
|
|
147
|
+
if (!seen || Number(job.attempt ?? 0) >= Number(seen.attempt ?? 0))
|
|
148
|
+
newest.set(name, job);
|
|
149
|
+
}
|
|
150
|
+
const pipelineUrl = `${ctx.web}/${ctx.repo}/pipelines/${pipeline.iid}`;
|
|
151
|
+
const runs = [...newest.values()].map(job => {
|
|
152
|
+
const state = gitboyState(job.status, job.allow_failure === true);
|
|
153
|
+
const seconds = job.started_at && job.finished_at ? Math.max(0, Math.round((Date.parse(String(job.finished_at)) - Date.parse(String(job.started_at))) / 1000)) : undefined;
|
|
154
|
+
return { name: String(job.name ?? "Job").slice(0, 200), state, ...(job.stage ? { workflow: String(job.stage).slice(0, 200) } : {}),
|
|
155
|
+
url: job.id ? `${pipelineUrl}?job=${encodeURIComponent(String(job.id))}` : pipelineUrl,
|
|
156
|
+
...(seconds !== undefined && Number.isFinite(seconds) ? { seconds } : {}),
|
|
157
|
+
...(typeof job.failure_reason === "string" && job.failure_reason ? { detail: job.failure_reason.slice(0, 300) } : {}) };
|
|
158
|
+
}).sort((a, b) => ORDER[a.state] - ORDER[b.state]).slice(0, 100);
|
|
159
|
+
return { runs, pipeline: { id: pipeline.iid, state: gitboyState(obj(detail).status ?? pipeline.status), url: pipelineUrl } };
|
|
160
|
+
}
|
|
161
|
+
/** Commit statuses, when there is no pipeline to read jobs from. */
|
|
162
|
+
function statusRuns(pull) {
|
|
163
|
+
return rows(pull.checks).filter(check => check.context !== "gitboy/pipeline").map(check => {
|
|
164
|
+
const url = safeLink(check.target_url);
|
|
165
|
+
return { name: String(check.context ?? "Check").replace(/^gitboy\//, "").slice(0, 200), state: gitboyState(check.state), ...(url ? { url } : {}) };
|
|
166
|
+
}).sort((a, b) => ORDER[a.state] - ORDER[b.state]).slice(0, 100);
|
|
167
|
+
}
|
|
168
|
+
function rollup(runs) {
|
|
169
|
+
if (!runs.length)
|
|
170
|
+
return null;
|
|
171
|
+
const states = runs.map(run => run.state);
|
|
172
|
+
if (states.includes("failing"))
|
|
173
|
+
return "failing";
|
|
174
|
+
return states.includes("pending") ? "pending" : "passing";
|
|
175
|
+
}
|
|
176
|
+
async function currentRequest(ctx, branch) {
|
|
177
|
+
if (!branch)
|
|
178
|
+
return null;
|
|
179
|
+
// gitboy can't filter by head branch: read the newest and pick this branch's.
|
|
180
|
+
const { json } = await call(ctx, `/pulls?state=all&limit=100&head_branch=${encodeURIComponent(branch)}`);
|
|
181
|
+
const mine = rows(json).filter(pull => pull.head_branch === branch && sameRepository(ctx, pull))
|
|
182
|
+
.sort((a, b) => Number(stateOf(b) === "OPEN") - Number(stateOf(a) === "OPEN") || String(b.updated_at ?? "").localeCompare(String(a.updated_at ?? "")))[0];
|
|
183
|
+
const index = mine?.index ?? mine?.number;
|
|
184
|
+
if (index === undefined)
|
|
185
|
+
return null;
|
|
186
|
+
const { json: detail } = await call(ctx, `/pulls/${index}`);
|
|
187
|
+
const pull = obj(detail);
|
|
188
|
+
const { runs: jobs, pipeline } = await jobsFor(ctx, pull);
|
|
189
|
+
const checkRuns = jobs.length ? jobs : statusRuns(pull);
|
|
190
|
+
const reviewDecision = gitboyReviewDecision(pull);
|
|
191
|
+
const approvals = new Set(rows(pull.reviews).filter(review => review.state === "approved" && review.reviewer_username !== pull.author_username
|
|
192
|
+
&& (!pull.head_sha || review.commit_sha === pull.head_sha)).map(review => String(review.reviewer_username ?? review.reviewer_id))).size;
|
|
193
|
+
const conflicted = Array.isArray(pull.conflicted_files) ? pull.conflicted_files.length : 0;
|
|
194
|
+
return { ...listed(ctx, pull), checks: rollup(checkRuns), checkRuns,
|
|
195
|
+
...(reviewDecision ? { reviewDecision } : {}),
|
|
196
|
+
...gitboyMergeState(pull),
|
|
197
|
+
...(pipeline ? { pipeline } : {}),
|
|
198
|
+
...(approvals ? { approvals: { given: approvals } } : {}),
|
|
199
|
+
...(typeof pull.comment_count === "number" ? { comments: pull.comment_count } : Array.isArray(pull.comments) ? { comments: pull.comments.length } : {}),
|
|
200
|
+
...(typeof pull.commits_behind === "number" ? { behind: pull.commits_behind } : {}),
|
|
201
|
+
...(typeof pull.commits_ahead === "number" ? { ahead: pull.commits_ahead } : {}),
|
|
202
|
+
...(conflicted ? { conflicts: true } : {}),
|
|
203
|
+
...(typeof pull.head_sha === "string" ? { headSha: pull.head_sha } : {}) };
|
|
204
|
+
}
|
|
205
|
+
function failed(error, domain) {
|
|
206
|
+
if (error instanceof HostApiError)
|
|
207
|
+
return { available: false, reason: error.reason, message: error.reason === "auth" ? `${error.message} ${SIGN_IN(domain)}` : error.message, pulls: [], current: null };
|
|
208
|
+
return { available: false, reason: "failed", message: error instanceof Error ? error.message : String(error), pulls: [], current: null };
|
|
209
|
+
}
|
|
210
|
+
/** Whether this gitboy has draft pull requests: any pull request it lists
|
|
211
|
+
* carries a `draft` key. */
|
|
212
|
+
async function hasDraftState(ctx, listed) {
|
|
213
|
+
const sample = rows(listed).length ? rows(listed) : rows((await call(ctx, "/pulls?state=all&limit=1").catch(() => ({ json: [] }))).json);
|
|
214
|
+
return sample.some(pull => typeof pull.draft === "boolean");
|
|
215
|
+
}
|
|
216
|
+
export const gitboy = {
|
|
217
|
+
kind: "gitboy",
|
|
218
|
+
name: "gitboy",
|
|
219
|
+
terms: PULL_TERMS,
|
|
220
|
+
supported: true,
|
|
221
|
+
async list(root, branch, host) {
|
|
222
|
+
const ctx = await context(root, host);
|
|
223
|
+
if (!("api" in ctx))
|
|
224
|
+
return ctx;
|
|
225
|
+
try {
|
|
226
|
+
const [{ json }, current] = await Promise.all([call(ctx, "/pulls?state=open&limit=50"), currentRequest(ctx, branch)]);
|
|
227
|
+
return { available: true, pulls: rows(json).map(pull => listed(ctx, pull)), current, account: ctx.account };
|
|
228
|
+
}
|
|
229
|
+
catch (error) {
|
|
230
|
+
return failed(error, ctx.domain);
|
|
231
|
+
}
|
|
232
|
+
},
|
|
233
|
+
async open(root, branch, draft, host) {
|
|
234
|
+
const ctx = await context(root, host);
|
|
235
|
+
if (!("api" in ctx))
|
|
236
|
+
return { ok: false, reason: ctx.reason, message: ctx.message };
|
|
237
|
+
try {
|
|
238
|
+
const { json: open } = await call(ctx, `/pulls?state=open&limit=100&head_branch=${encodeURIComponent(branch)}`);
|
|
239
|
+
const existing = rows(open).find(pull => pull.head_branch === branch);
|
|
240
|
+
if (existing)
|
|
241
|
+
return { ok: true, url: pullUrl(ctx, existing), number: existing.index, branch, existing: true };
|
|
242
|
+
const { json: repo } = await call(ctx, "");
|
|
243
|
+
const target = String(obj(repo).default_branch ?? "main");
|
|
244
|
+
const fill = await fillFromCommits(root, `${host.remote ?? "origin"}/${target}`, branch);
|
|
245
|
+
// A gitboy with draft pull requests sends `draft` on every one; an older
|
|
246
|
+
// one has none, and the title says it, as GitLab's convention does.
|
|
247
|
+
const native = draft && await hasDraftState(ctx, open);
|
|
248
|
+
const title = draft && !native && !/^draft:/i.test(fill.title) ? `Draft: ${fill.title}` : fill.title;
|
|
249
|
+
const { json } = await call(ctx, "/pulls", { method: "POST", body: { head_branch: branch, base_branch: target, title, body: fill.body, ...(native ? { draft: true } : {}) } });
|
|
250
|
+
const pull = obj(json);
|
|
251
|
+
return { ok: true, url: pullUrl(ctx, pull), number: (pull.index ?? pull.number), branch, draft };
|
|
252
|
+
}
|
|
253
|
+
catch (error) {
|
|
254
|
+
if (error instanceof HostApiError && error.status === 400 && /no changes|nothing to compare|no mergeable changes|choose different source and target/i.test(error.message))
|
|
255
|
+
return { ok: false, reason: "failed", message: `${branch} has no changes against the default branch.` };
|
|
256
|
+
// gitboy answers 500 (not 404) for a branch it doesn't have yet; ask git.
|
|
257
|
+
if (error instanceof HostApiError && (error.status === 404 || error.status === 500) && !await remoteHasBranch(root, host.remote ?? "origin", branch)) {
|
|
258
|
+
return { ok: false, reason: "not-found", message: `Push ${branch} to gitboy first, then open the pull request.` };
|
|
259
|
+
}
|
|
260
|
+
const result = failed(error, ctx.domain);
|
|
261
|
+
return { ok: false, reason: result.reason ?? "failed", message: result.message ?? "gitboy refused the pull request." };
|
|
262
|
+
}
|
|
263
|
+
},
|
|
264
|
+
async merge(root, request, host) {
|
|
265
|
+
const ctx = await context(root, host);
|
|
266
|
+
if (!("api" in ctx))
|
|
267
|
+
return { ok: false, reason: ctx.reason, message: ctx.message };
|
|
268
|
+
try {
|
|
269
|
+
// gitboy needs both heads for a rebase; the base guard is harmless for the others.
|
|
270
|
+
const { json: detail } = await call(ctx, `/pulls/${request.number}`).catch(() => ({ json: {} }));
|
|
271
|
+
const baseSha = typeof obj(detail).base_sha === "string" ? obj(detail).base_sha : undefined;
|
|
272
|
+
const { json } = await call(ctx, `/pulls/${request.number}/merge`, { method: "POST", body: {
|
|
273
|
+
method: request.method, ...(request.expectedHeadSha ? { expected_head_sha: request.expectedHeadSha } : {}),
|
|
274
|
+
...(baseSha ? { expected_base_sha: baseSha } : {})
|
|
275
|
+
} });
|
|
276
|
+
const result = obj(json);
|
|
277
|
+
return { ok: true, number: request.number, method: request.method, ...(typeof result.merge_commit_sha === "string" ? { mergeCommit: result.merge_commit_sha } : {}) };
|
|
278
|
+
}
|
|
279
|
+
catch (error) {
|
|
280
|
+
if (error instanceof HostApiError && (error.status === 409 || error.status === 422 || error.status === 400)) {
|
|
281
|
+
return { ok: false, reason: "blocked", message: refusalReasons(error) };
|
|
282
|
+
}
|
|
283
|
+
if (error instanceof HostApiError && error.status === 403)
|
|
284
|
+
return { ok: false, reason: "auth", message: "The gitboy token can read but not merge here; it needs write:repo, and your account needs merge rights on the branch." };
|
|
285
|
+
const result = failed(error, ctx.domain);
|
|
286
|
+
return { ok: false, reason: result.reason ?? "failed", message: result.message ?? "gitboy refused the merge." };
|
|
287
|
+
}
|
|
288
|
+
},
|
|
289
|
+
async whoami(root, host, token) {
|
|
290
|
+
if (!host.domain)
|
|
291
|
+
throw new HostApiError("failed", "This repository has no gitboy remote.");
|
|
292
|
+
const api = await apiRoot(root, host.domain, `https://${host.domain}/api/v1`);
|
|
293
|
+
const { json } = await hostJson(`${api}/user`, { token, scheme: "bearer" });
|
|
294
|
+
return { user: String(obj(json).username ?? "") };
|
|
295
|
+
},
|
|
296
|
+
};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { GitHostProvider, HostTerms } from "./git-hosts.js";
|
|
2
|
+
/** GitLab, gitlab.com or self-hosted, over its REST API (v4). The token is
|
|
3
|
+
* GITLAB_TOKEN, the Hook's stored one, or glab's own sign-in, so glab itself
|
|
4
|
+
* is optional. Merge requests come back in the same shape as GitHub's pull
|
|
5
|
+
* requests; pipeline jobs are the checks, and the stage reads as the workflow. */
|
|
6
|
+
export declare const MERGE_TERMS: HostTerms;
|
|
7
|
+
type Order = "failing" | "pending" | "passing" | "skipped" | "neutral";
|
|
8
|
+
/** A pipeline or job status as one state word. An allowed failure is neutral:
|
|
9
|
+
* it doesn't block the merge request. */
|
|
10
|
+
export declare function gitlabState(status: unknown, allowFailure?: boolean): Order;
|
|
11
|
+
export declare function gitlabRollup(states: Order[]): "passing" | "failing" | "pending" | null;
|
|
12
|
+
/** What `detailed_merge_status` means, in GitHub's mergeStateStatus words
|
|
13
|
+
* (which the clients already colour) plus GitLab's own sentence. */
|
|
14
|
+
export declare function gitlabMergeState(detail: unknown): {
|
|
15
|
+
mergeState?: string;
|
|
16
|
+
mergeDetail?: string;
|
|
17
|
+
};
|
|
18
|
+
/** gh's --fill: one commit gives the title and body; several give a title from
|
|
19
|
+
* the branch and a body listing them. */
|
|
20
|
+
export declare function fillFromCommits(root: string, baseRef: string, branch: string): Promise<{
|
|
21
|
+
title: string;
|
|
22
|
+
body: string;
|
|
23
|
+
}>;
|
|
24
|
+
export declare const gitlab: GitHostProvider;
|
|
25
|
+
export {};
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { resolveHostToken } from "./git-host-auth.js";
|
|
2
|
+
import { apiRoot, HostApiError, hostJson, safeLink } from "./git-host-http.js";
|
|
3
|
+
import { git } from "./projects.js";
|
|
4
|
+
/** GitLab, gitlab.com or self-hosted, over its REST API (v4). The token is
|
|
5
|
+
* GITLAB_TOKEN, the Hook's stored one, or glab's own sign-in, so glab itself
|
|
6
|
+
* is optional. Merge requests come back in the same shape as GitHub's pull
|
|
7
|
+
* requests; pipeline jobs are the checks, and the stage reads as the workflow. */
|
|
8
|
+
export const MERGE_TERMS = { short: "MR", long: "merge request", ref: "!" };
|
|
9
|
+
const ORDER = { failing: 0, pending: 1, passing: 2, skipped: 3, neutral: 4 };
|
|
10
|
+
/** A pipeline or job status as one state word. An allowed failure is neutral:
|
|
11
|
+
* it doesn't block the merge request. */
|
|
12
|
+
export function gitlabState(status, allowFailure = false) {
|
|
13
|
+
switch (String(status ?? "").toLowerCase()) {
|
|
14
|
+
case "success": return "passing";
|
|
15
|
+
case "failed": return allowFailure ? "neutral" : "failing";
|
|
16
|
+
case "canceled":
|
|
17
|
+
case "canceling": return allowFailure ? "neutral" : "failing";
|
|
18
|
+
case "skipped": return "skipped";
|
|
19
|
+
case "manual": return "neutral";
|
|
20
|
+
default: return "pending"; // created, waiting_for_resource, preparing, pending, running, scheduled
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export function gitlabRollup(states) {
|
|
24
|
+
if (!states.length)
|
|
25
|
+
return null;
|
|
26
|
+
if (states.includes("failing"))
|
|
27
|
+
return "failing";
|
|
28
|
+
return states.includes("pending") ? "pending" : "passing";
|
|
29
|
+
}
|
|
30
|
+
/** What `detailed_merge_status` means, in GitHub's mergeStateStatus words
|
|
31
|
+
* (which the clients already colour) plus GitLab's own sentence. */
|
|
32
|
+
export function gitlabMergeState(detail) {
|
|
33
|
+
const value = String(detail ?? "");
|
|
34
|
+
const map = {
|
|
35
|
+
mergeable: ["CLEAN", "Ready to merge"],
|
|
36
|
+
conflict: ["DIRTY", "Has merge conflicts"],
|
|
37
|
+
need_rebase: ["BEHIND", "Needs a rebase onto the target branch"],
|
|
38
|
+
ci_must_pass: ["BLOCKED", "Waiting for the pipeline to pass"],
|
|
39
|
+
ci_still_running: ["BLOCKED", "Pipeline still running"],
|
|
40
|
+
not_approved: ["BLOCKED", "Needs approval"],
|
|
41
|
+
discussions_not_resolved: ["BLOCKED", "Has unresolved threads"],
|
|
42
|
+
draft_status: ["DRAFT", "Draft"],
|
|
43
|
+
blocked_status: ["BLOCKED", "Blocked by another merge request"],
|
|
44
|
+
requested_changes: ["BLOCKED", "Changes requested"],
|
|
45
|
+
jira_association_missing: ["BLOCKED", "Needs a Jira issue"],
|
|
46
|
+
merge_request_blocked: ["BLOCKED", "Blocked"],
|
|
47
|
+
external_status_checks: ["BLOCKED", "Waiting for external status checks"],
|
|
48
|
+
not_open: ["UNKNOWN", "Not open"],
|
|
49
|
+
checking: ["UNKNOWN", "Checking mergeability"],
|
|
50
|
+
unchecked: ["UNKNOWN", "Not checked yet"],
|
|
51
|
+
preparing: ["UNKNOWN", "Preparing"],
|
|
52
|
+
};
|
|
53
|
+
const hit = map[value];
|
|
54
|
+
return hit ? { mergeState: hit[0], mergeDetail: hit[1] } : value ? { mergeState: "UNKNOWN", mergeDetail: value.replace(/_/g, " ") } : {};
|
|
55
|
+
}
|
|
56
|
+
function upper(state) {
|
|
57
|
+
const value = String(state ?? "").toLowerCase();
|
|
58
|
+
return value === "opened" ? "OPEN" : value === "locked" ? "CLOSED" : value.toUpperCase();
|
|
59
|
+
}
|
|
60
|
+
function obj(value) {
|
|
61
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
62
|
+
}
|
|
63
|
+
function projectPath(host) {
|
|
64
|
+
if (!host.webUrl || !host.domain)
|
|
65
|
+
return null;
|
|
66
|
+
const path = host.webUrl.replace(/^https?:\/\/[^/]+\//, "");
|
|
67
|
+
return path || null;
|
|
68
|
+
}
|
|
69
|
+
const SIGN_IN = (domain) => `Phren has no GitLab token for ${domain}. Connect it from the desktop's Changes pane, run phren bridge git-host set ${domain} gitlab on this computer, or sign in with glab auth login.`;
|
|
70
|
+
async function context(root, host) {
|
|
71
|
+
const path = projectPath(host);
|
|
72
|
+
if (!host.domain || !path)
|
|
73
|
+
return { available: false, reason: "unknown-host", message: "This repository has no GitLab remote.", pulls: [], current: null };
|
|
74
|
+
const token = await resolveHostToken("gitlab", host.domain);
|
|
75
|
+
if (!token)
|
|
76
|
+
return { available: false, reason: "auth", message: SIGN_IN(host.domain), pulls: [], current: null };
|
|
77
|
+
const base = await apiRoot(root, host.domain, `https://${host.domain}/api/v4`);
|
|
78
|
+
return { base, token: token.token, project: encodeURIComponent(path), domain: host.domain, account: { source: token.source, ...(token.user ? { user: token.user } : {}) } };
|
|
79
|
+
}
|
|
80
|
+
function call(ctx, path, init = {}) {
|
|
81
|
+
return hostJson(`${ctx.base}/projects/${ctx.project}${path}`, { token: ctx.token, scheme: "private-token", ...init });
|
|
82
|
+
}
|
|
83
|
+
function listed(mr) {
|
|
84
|
+
const author = obj(mr.author);
|
|
85
|
+
return { number: mr.iid, title: String(mr.title ?? ""), head: String(mr.source_branch ?? ""), base: String(mr.target_branch ?? ""),
|
|
86
|
+
author: String(author.username ?? author.name ?? ""), url: safeLink(mr.web_url) ?? "", draft: mr.draft === true || mr.work_in_progress === true,
|
|
87
|
+
state: upper(mr.state), updated: String(mr.updated_at ?? "") };
|
|
88
|
+
}
|
|
89
|
+
/** The branch's merge request with its pipeline jobs, approvals and merge state. */
|
|
90
|
+
async function currentRequest(ctx, branch) {
|
|
91
|
+
if (!branch)
|
|
92
|
+
return null;
|
|
93
|
+
const { json: found } = await call(ctx, `/merge_requests?source_branch=${encodeURIComponent(branch)}&state=all&order_by=updated_at&per_page=5`);
|
|
94
|
+
const first = (Array.isArray(found) ? found : []).map(obj).sort((a, b) => Number(upper(b.state) === "OPEN") - Number(upper(a.state) === "OPEN"))[0];
|
|
95
|
+
if (!first || typeof first.iid !== "number")
|
|
96
|
+
return null;
|
|
97
|
+
const [{ json: detail }, approvals] = await Promise.all([
|
|
98
|
+
call(ctx, `/merge_requests/${first.iid}`),
|
|
99
|
+
call(ctx, `/merge_requests/${first.iid}/approvals`).then(r => obj(r.json)).catch(() => null),
|
|
100
|
+
]);
|
|
101
|
+
const mr = obj(detail);
|
|
102
|
+
const pipeline = obj(mr.head_pipeline ?? mr.pipeline);
|
|
103
|
+
let checkRuns = [];
|
|
104
|
+
if (typeof pipeline.id === "number") {
|
|
105
|
+
const { json: jobs } = await call(ctx, `/pipelines/${pipeline.id}/jobs?per_page=100&include_retried=false`).catch(() => ({ json: [] }));
|
|
106
|
+
checkRuns = (Array.isArray(jobs) ? jobs : []).map(obj).map(job => {
|
|
107
|
+
const state = gitlabState(job.status, job.allow_failure === true);
|
|
108
|
+
const url = safeLink(job.web_url);
|
|
109
|
+
return { name: String(job.name ?? "Job").slice(0, 200), state, ...(job.stage ? { workflow: String(job.stage).slice(0, 200) } : {}), ...(url ? { url } : {}),
|
|
110
|
+
...(typeof job.duration === "number" ? { seconds: Math.round(job.duration) } : {}) };
|
|
111
|
+
}).sort((a, b) => ORDER[a.state] - ORDER[b.state]).slice(0, 100);
|
|
112
|
+
}
|
|
113
|
+
const given = Array.isArray(approvals?.approved_by) ? approvals.approved_by.length : 0;
|
|
114
|
+
const left = typeof approvals?.approvals_left === "number" ? approvals.approvals_left : undefined;
|
|
115
|
+
const required = typeof approvals?.approvals_required === "number" ? approvals.approvals_required : undefined;
|
|
116
|
+
const reviewDecision = approvals?.approved === true && (left ?? 0) === 0 && (required ?? given) > 0 ? "APPROVED"
|
|
117
|
+
: (left ?? 0) > 0 ? "REVIEW_REQUIRED" : undefined;
|
|
118
|
+
const pipelineState = typeof pipeline.status === "string" ? gitlabState(pipeline.status) : null;
|
|
119
|
+
const checks = checkRuns.length ? gitlabRollup(checkRuns.map(run => run.state)) : pipelineState === "neutral" || pipelineState === "skipped" ? "passing" : pipelineState;
|
|
120
|
+
const pipelineUrl = safeLink(pipeline.web_url);
|
|
121
|
+
return { ...listed(mr), checks, checkRuns,
|
|
122
|
+
...(reviewDecision ? { reviewDecision } : {}),
|
|
123
|
+
...gitlabMergeState(mr.detailed_merge_status ?? mr.merge_status),
|
|
124
|
+
...(typeof pipeline.id === "number" ? { pipeline: { id: pipeline.id, state: pipelineState, ...(pipelineUrl ? { url: pipelineUrl } : {}) } } : {}),
|
|
125
|
+
...(given || required !== undefined ? { approvals: { given, ...(required !== undefined ? { required } : {}) } } : {}),
|
|
126
|
+
...(typeof mr.user_notes_count === "number" ? { comments: mr.user_notes_count } : {}),
|
|
127
|
+
...(mr.has_conflicts === true ? { conflicts: true } : {}) };
|
|
128
|
+
}
|
|
129
|
+
function failed(error, domain) {
|
|
130
|
+
if (error instanceof HostApiError) {
|
|
131
|
+
const message = error.reason === "auth" ? `${error.message} ${SIGN_IN(domain)}` : error.message;
|
|
132
|
+
return { available: false, reason: error.reason, message, pulls: [], current: null };
|
|
133
|
+
}
|
|
134
|
+
return { available: false, reason: "failed", message: error instanceof Error ? error.message : String(error), pulls: [], current: null };
|
|
135
|
+
}
|
|
136
|
+
/** gh's --fill: one commit gives the title and body; several give a title from
|
|
137
|
+
* the branch and a body listing them. */
|
|
138
|
+
export async function fillFromCommits(root, baseRef, branch) {
|
|
139
|
+
const raw = await git(root, "log", "--reverse", "--format=%s%x1f%b%x1e", `${baseRef}..${branch}`).catch(() => "");
|
|
140
|
+
const commits = raw.split("\x1e").map(entry => entry.trim()).filter(Boolean).map(entry => { const [subject, body = ""] = entry.split("\x1f"); return { subject: subject.trim(), body: body.trim() }; });
|
|
141
|
+
if (commits.length === 1)
|
|
142
|
+
return { title: commits[0].subject, body: commits[0].body };
|
|
143
|
+
const words = branch.replace(/^[^/]+\//, "").replace(/[-_]+/g, " ").trim();
|
|
144
|
+
const title = words ? words[0].toUpperCase() + words.slice(1) : branch;
|
|
145
|
+
return { title, body: commits.map(commit => `- ${commit.subject}`).join("\n") };
|
|
146
|
+
}
|
|
147
|
+
export const gitlab = {
|
|
148
|
+
kind: "gitlab",
|
|
149
|
+
name: "GitLab",
|
|
150
|
+
terms: MERGE_TERMS,
|
|
151
|
+
supported: true,
|
|
152
|
+
async list(root, branch, host) {
|
|
153
|
+
const ctx = await context(root, host);
|
|
154
|
+
if (!("base" in ctx))
|
|
155
|
+
return ctx;
|
|
156
|
+
try {
|
|
157
|
+
const [{ json }, current] = await Promise.all([
|
|
158
|
+
call(ctx, "/merge_requests?state=opened&order_by=updated_at&per_page=50"),
|
|
159
|
+
currentRequest(ctx, branch),
|
|
160
|
+
]);
|
|
161
|
+
return { available: true, pulls: (Array.isArray(json) ? json : []).map(obj).map(listed), current, account: ctx.account };
|
|
162
|
+
}
|
|
163
|
+
catch (error) {
|
|
164
|
+
return failed(error, ctx.domain);
|
|
165
|
+
}
|
|
166
|
+
},
|
|
167
|
+
async open(root, branch, draft, host) {
|
|
168
|
+
const ctx = await context(root, host);
|
|
169
|
+
if (!("base" in ctx))
|
|
170
|
+
return { ok: false, reason: ctx.reason, message: ctx.message };
|
|
171
|
+
try {
|
|
172
|
+
await call(ctx, `/repository/branches/${encodeURIComponent(branch)}`).catch(error => {
|
|
173
|
+
if (error instanceof HostApiError && error.reason === "not-found")
|
|
174
|
+
throw new HostApiError("not-found", `Push ${branch} to GitLab first, then open the merge request.`, 404);
|
|
175
|
+
throw error;
|
|
176
|
+
});
|
|
177
|
+
const { json: project } = await call(ctx, "");
|
|
178
|
+
const target = String(obj(project).default_branch ?? "main");
|
|
179
|
+
const fill = await fillFromCommits(root, `${host.remote ?? "origin"}/${target}`, branch);
|
|
180
|
+
const title = draft && !/^draft:/i.test(fill.title) ? `Draft: ${fill.title}` : fill.title;
|
|
181
|
+
try {
|
|
182
|
+
const { json } = await call(ctx, "/merge_requests", { method: "POST", body: { source_branch: branch, target_branch: target, title, description: fill.body, remove_source_branch: true } });
|
|
183
|
+
return { ok: true, url: safeLink(obj(json).web_url) ?? "", number: obj(json).iid, branch, draft };
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
if (error instanceof HostApiError && error.status === 409) {
|
|
187
|
+
const { json } = await call(ctx, `/merge_requests?source_branch=${encodeURIComponent(branch)}&state=opened&per_page=1`);
|
|
188
|
+
const existing = (Array.isArray(json) ? json : []).map(obj)[0];
|
|
189
|
+
if (existing)
|
|
190
|
+
return { ok: true, url: safeLink(existing.web_url) ?? "", number: existing.iid, branch, existing: true };
|
|
191
|
+
}
|
|
192
|
+
throw error;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
catch (error) {
|
|
196
|
+
const result = failed(error, ctx.domain);
|
|
197
|
+
return { ok: false, reason: result.reason ?? "failed", message: result.message ?? "GitLab refused the merge request." };
|
|
198
|
+
}
|
|
199
|
+
},
|
|
200
|
+
async merge(root, request, host) {
|
|
201
|
+
const ctx = await context(root, host);
|
|
202
|
+
if (!("base" in ctx))
|
|
203
|
+
return { ok: false, reason: ctx.reason, message: ctx.message };
|
|
204
|
+
try {
|
|
205
|
+
// GitLab merges, or rebases, by the project's own merge method; squash is per request.
|
|
206
|
+
const { json } = await call(ctx, `/merge_requests/${request.number}/merge`, { method: "PUT", body: {
|
|
207
|
+
squash: request.method === "squash", ...(request.expectedHeadSha ? { sha: request.expectedHeadSha } : {}),
|
|
208
|
+
...(request.deleteBranch ? { should_remove_source_branch: true } : {})
|
|
209
|
+
} });
|
|
210
|
+
const mr = obj(json);
|
|
211
|
+
return { ok: true, number: request.number, method: request.method, state: upper(mr.state), ...(safeLink(mr.web_url) ? { url: safeLink(mr.web_url) } : {}) };
|
|
212
|
+
}
|
|
213
|
+
catch (error) {
|
|
214
|
+
if (error instanceof HostApiError && [405, 406, 409, 422].includes(error.status)) {
|
|
215
|
+
const why = error.status === 409 ? "The merge request has new commits since you looked; refresh and check them first." : error.message.replace(/^.*? answered \d+:? ?/, "") || "GitLab says it can't be merged yet.";
|
|
216
|
+
return { ok: false, reason: "blocked", message: why };
|
|
217
|
+
}
|
|
218
|
+
const result = failed(error, ctx.domain);
|
|
219
|
+
return { ok: false, reason: result.reason ?? "failed", message: result.message ?? "GitLab refused the merge." };
|
|
220
|
+
}
|
|
221
|
+
},
|
|
222
|
+
async whoami(root, host, token) {
|
|
223
|
+
if (!host.domain)
|
|
224
|
+
throw new HostApiError("failed", "This repository has no GitLab remote.");
|
|
225
|
+
const base = await apiRoot(root, host.domain, `https://${host.domain}/api/v4`);
|
|
226
|
+
const { json } = await hostJson(`${base}/user`, { token, scheme: "private-token" });
|
|
227
|
+
return { user: String(obj(json).username ?? "") };
|
|
228
|
+
},
|
|
229
|
+
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { Json } from "./protocol.js";
|
|
2
|
+
/** A small JSON client for the git hosts the Hook reads over HTTP. Every call
|
|
3
|
+
* has a deadline, never follows a redirect to another origin with the token,
|
|
4
|
+
* and turns a host's refusal into one of a few reasons clients can act on. */
|
|
5
|
+
export type HostFailure = "auth" | "not-found" | "unreachable" | "failed";
|
|
6
|
+
export declare class HostApiError extends Error {
|
|
7
|
+
reason: HostFailure;
|
|
8
|
+
status: number;
|
|
9
|
+
body: unknown;
|
|
10
|
+
/** `body` is the host's own JSON for a refusal (gitboy's `details`, say). */
|
|
11
|
+
constructor(reason: HostFailure, message: string, status?: number, body?: unknown);
|
|
12
|
+
}
|
|
13
|
+
/** The API root for a domain: `git config --global phren.<domain>.api` when
|
|
14
|
+
* set (a self-hosted server on another port or path), else the host's
|
|
15
|
+
* default. Only the user's global config counts: a repository's own config is
|
|
16
|
+
* writable by whatever runs in the checkout, and must never be able to send
|
|
17
|
+
* a stored token to another server. */
|
|
18
|
+
export declare function apiRoot(root: string, domain: string, fallback: string): Promise<string>;
|
|
19
|
+
export interface HostRequest {
|
|
20
|
+
token?: string;
|
|
21
|
+
/** How the token is sent: GitLab's PRIVATE-TOKEN header or a bearer token. */
|
|
22
|
+
scheme: "private-token" | "bearer";
|
|
23
|
+
method?: "GET" | "POST" | "PUT";
|
|
24
|
+
body?: Json;
|
|
25
|
+
timeoutMs?: number;
|
|
26
|
+
}
|
|
27
|
+
export declare function hostJson<T = unknown>(url: string, request: HostRequest): Promise<{
|
|
28
|
+
status: number;
|
|
29
|
+
json: T;
|
|
30
|
+
headers: Headers;
|
|
31
|
+
}>;
|
|
32
|
+
/** An https link, or nothing: hosts' links are shown and opened as-is. */
|
|
33
|
+
export declare function safeLink(value: unknown): string | undefined;
|