@brain-toolkit/issue-forge 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/LICENSE +15 -0
- package/README.md +1 -2
- package/dist/chunk-MQ7IDBIZ.js +4 -0
- package/dist/{chunk-RQKDVDLH.js.map → chunk-MQ7IDBIZ.js.map} +1 -1
- package/dist/feedback/index.cjs +4 -871
- package/dist/feedback/index.cjs.map +1 -1
- package/dist/feedback/index.js +4 -527
- package/dist/feedback/index.js.map +1 -1
- package/dist/index.cjs +3 -514
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -22
- package/package.json +19 -33
- package/dist/chunk-RQKDVDLH.js +0 -471
package/dist/index.cjs
CHANGED
|
@@ -1,515 +1,4 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
var
|
|
4
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __export = (target, all) => {
|
|
9
|
-
for (var name in all)
|
|
10
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
-
};
|
|
12
|
-
var __copyProps = (to, from, except, desc) => {
|
|
13
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
-
for (let key of __getOwnPropNames(from))
|
|
15
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
-
}
|
|
18
|
-
return to;
|
|
19
|
-
};
|
|
20
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
-
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
-
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
-
mod
|
|
27
|
-
));
|
|
28
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
-
|
|
30
|
-
// src/index.ts
|
|
31
|
-
var src_exports = {};
|
|
32
|
-
__export(src_exports, {
|
|
33
|
-
GithubAppClient: () => GithubAppClient,
|
|
34
|
-
GithubAppIssueForgeGateway: () => GithubAppIssueForgeGateway,
|
|
35
|
-
GithubAppRepoContentGateway: () => GithubAppRepoContentGateway,
|
|
36
|
-
GithubWebhookVerifier: () => GithubWebhookVerifier,
|
|
37
|
-
IssueForgeError: () => IssueForgeError,
|
|
38
|
-
createGithubAppClient: () => createGithubAppClient,
|
|
39
|
-
createGithubAppIssueForge: () => createGithubAppIssueForge,
|
|
40
|
-
createGithubAppRepoContent: () => createGithubAppRepoContent,
|
|
41
|
-
createGithubWebhookVerifier: () => createGithubWebhookVerifier
|
|
42
|
-
});
|
|
43
|
-
module.exports = __toCommonJS(src_exports);
|
|
44
|
-
|
|
45
|
-
// src/errors/IssueForgeError.ts
|
|
46
|
-
var IssueForgeError = class extends Error {
|
|
47
|
-
code = "ISSUE_FORGE_FAILED";
|
|
48
|
-
/** HTTP 状态码;网络错误等无响应时为 null */
|
|
49
|
-
status;
|
|
50
|
-
constructor(message, status) {
|
|
51
|
-
super(message);
|
|
52
|
-
this.name = "IssueForgeError";
|
|
53
|
-
this.status = status;
|
|
54
|
-
}
|
|
55
|
-
};
|
|
56
|
-
|
|
57
|
-
// src/github/GithubAppClient.ts
|
|
58
|
-
var import_jsonwebtoken = __toESM(require("jsonwebtoken"), 1);
|
|
59
|
-
var GITHUB_API = "https://api.github.com";
|
|
60
|
-
var GITHUB_API_VERSION = "2022-11-28";
|
|
61
|
-
var DEFAULT_USER_AGENT = "brain-toolkit-issue-forge";
|
|
62
|
-
var REQUEST_TIMEOUT_MS = 6e4;
|
|
63
|
-
var APP_JWT_TTL_SEC = 9 * 60;
|
|
64
|
-
var APP_JWT_CLOCK_SKEW_SEC = 60;
|
|
65
|
-
var TOKEN_REFRESH_MARGIN_MS = 2 * 60 * 1e3;
|
|
66
|
-
var GithubAppClient = class {
|
|
67
|
-
cache;
|
|
68
|
-
userAgent;
|
|
69
|
-
constructor(options) {
|
|
70
|
-
this.cache = options.cache;
|
|
71
|
-
this.userAgent = options.userAgent?.trim() || DEFAULT_USER_AGENT;
|
|
72
|
-
}
|
|
73
|
-
async request(config, path, init) {
|
|
74
|
-
const token = await this.getInstallationToken(config);
|
|
75
|
-
const headers = this.headers(`Bearer ${token}`);
|
|
76
|
-
if (init.accept) {
|
|
77
|
-
headers.Accept = init.accept;
|
|
78
|
-
}
|
|
79
|
-
if (init.body !== void 0) {
|
|
80
|
-
headers["Content-Type"] = "application/json";
|
|
81
|
-
}
|
|
82
|
-
const response = await this.send(`${GITHUB_API}${path}`, {
|
|
83
|
-
method: init.method,
|
|
84
|
-
headers,
|
|
85
|
-
...init.body !== void 0 ? { body: JSON.stringify(init.body) } : {}
|
|
86
|
-
});
|
|
87
|
-
if (response.status === 401 || response.status === 403) {
|
|
88
|
-
await this.cache.removeItem(this.tokenCacheKey(config));
|
|
89
|
-
}
|
|
90
|
-
return response;
|
|
91
|
-
}
|
|
92
|
-
async toError(stage, response) {
|
|
93
|
-
let detail = "";
|
|
94
|
-
try {
|
|
95
|
-
const json = await response.json();
|
|
96
|
-
detail = typeof json.message === "string" ? json.message : "";
|
|
97
|
-
} catch {
|
|
98
|
-
detail = "";
|
|
99
|
-
}
|
|
100
|
-
return new IssueForgeError(
|
|
101
|
-
`${stage}: HTTP ${String(response.status)}${detail ? ` ${detail}` : ""}`,
|
|
102
|
-
response.status
|
|
103
|
-
);
|
|
104
|
-
}
|
|
105
|
-
async getInstallationToken(config) {
|
|
106
|
-
const cacheKey = this.tokenCacheKey(config);
|
|
107
|
-
const cached = await this.cache.getItem(cacheKey);
|
|
108
|
-
if (cached?.token) {
|
|
109
|
-
return cached.token;
|
|
110
|
-
}
|
|
111
|
-
const response = await this.send(
|
|
112
|
-
`${GITHUB_API}/app/installations/${encodeURIComponent(config.installationId)}/access_tokens`,
|
|
113
|
-
{
|
|
114
|
-
method: "POST",
|
|
115
|
-
headers: this.headers(`Bearer ${this.signAppJwt(config)}`)
|
|
116
|
-
}
|
|
117
|
-
);
|
|
118
|
-
if (!response.ok) {
|
|
119
|
-
throw await this.toError("installation token", response);
|
|
120
|
-
}
|
|
121
|
-
const json = await response.json();
|
|
122
|
-
if (typeof json.token !== "string" || !json.token) {
|
|
123
|
-
throw new IssueForgeError(
|
|
124
|
-
"installation token: empty token",
|
|
125
|
-
response.status
|
|
126
|
-
);
|
|
127
|
-
}
|
|
128
|
-
const expiresAtMs = typeof json.expires_at === "string" ? Date.parse(json.expires_at) : Number.NaN;
|
|
129
|
-
const ttlMs = Number.isFinite(expiresAtMs) ? expiresAtMs - Date.now() - TOKEN_REFRESH_MARGIN_MS : 0;
|
|
130
|
-
if (ttlMs > 0) {
|
|
131
|
-
await this.cache.setItem(
|
|
132
|
-
cacheKey,
|
|
133
|
-
{ token: json.token },
|
|
134
|
-
{ ttlMs }
|
|
135
|
-
);
|
|
136
|
-
}
|
|
137
|
-
return json.token;
|
|
138
|
-
}
|
|
139
|
-
signAppJwt(config) {
|
|
140
|
-
const nowSec = Math.floor(Date.now() / 1e3);
|
|
141
|
-
try {
|
|
142
|
-
return import_jsonwebtoken.default.sign(
|
|
143
|
-
{
|
|
144
|
-
iat: nowSec - APP_JWT_CLOCK_SKEW_SEC,
|
|
145
|
-
exp: nowSec + APP_JWT_TTL_SEC,
|
|
146
|
-
iss: config.appId
|
|
147
|
-
},
|
|
148
|
-
this.normalizePrivateKey(config.privateKey),
|
|
149
|
-
{ algorithm: "RS256" }
|
|
150
|
-
);
|
|
151
|
-
} catch (error) {
|
|
152
|
-
throw new IssueForgeError(
|
|
153
|
-
`invalid GitHub App private key: ${error instanceof Error ? error.message : String(error)}`,
|
|
154
|
-
null
|
|
155
|
-
);
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
normalizePrivateKey(raw) {
|
|
159
|
-
return raw.replace(/\\n/g, "\n").replace(/\r\n/g, "\n").trim();
|
|
160
|
-
}
|
|
161
|
-
async send(url, init) {
|
|
162
|
-
try {
|
|
163
|
-
return await fetch(url, {
|
|
164
|
-
...init,
|
|
165
|
-
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
166
|
-
});
|
|
167
|
-
} catch (error) {
|
|
168
|
-
throw new IssueForgeError(
|
|
169
|
-
`GitHub request failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
170
|
-
null
|
|
171
|
-
);
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
headers(authorization) {
|
|
175
|
-
return {
|
|
176
|
-
Accept: "application/vnd.github+json",
|
|
177
|
-
Authorization: authorization,
|
|
178
|
-
"User-Agent": this.userAgent,
|
|
179
|
-
"X-GitHub-Api-Version": GITHUB_API_VERSION
|
|
180
|
-
};
|
|
181
|
-
}
|
|
182
|
-
tokenCacheKey(config) {
|
|
183
|
-
return `issue-forge:github:installation-token:${config.appId}:${config.installationId}`;
|
|
184
|
-
}
|
|
185
|
-
};
|
|
186
|
-
|
|
187
|
-
// src/github/GithubAppRepoContentGateway.ts
|
|
188
|
-
var ACCEPT_RAW = "application/vnd.github.raw+json";
|
|
189
|
-
var GithubAppRepoContentGateway = class {
|
|
190
|
-
constructor(client, config) {
|
|
191
|
-
this.client = client;
|
|
192
|
-
this.config = config;
|
|
193
|
-
}
|
|
194
|
-
/**
|
|
195
|
-
* @override
|
|
196
|
-
*/
|
|
197
|
-
async readTextFile(path) {
|
|
198
|
-
const response = await this.client.request(
|
|
199
|
-
this.config,
|
|
200
|
-
this.contentsPath(path),
|
|
201
|
-
{ method: "GET", accept: ACCEPT_RAW }
|
|
202
|
-
);
|
|
203
|
-
if (response.status === 404) {
|
|
204
|
-
return null;
|
|
205
|
-
}
|
|
206
|
-
if (!response.ok) {
|
|
207
|
-
throw await this.client.toError("read file", response);
|
|
208
|
-
}
|
|
209
|
-
return response.text();
|
|
210
|
-
}
|
|
211
|
-
/**
|
|
212
|
-
* @override
|
|
213
|
-
*/
|
|
214
|
-
async hasFile(path, branch) {
|
|
215
|
-
const response = await this.client.request(
|
|
216
|
-
this.config,
|
|
217
|
-
`${this.contentsPath(path)}?ref=${encodeURIComponent(branch)}`,
|
|
218
|
-
{ method: "GET" }
|
|
219
|
-
);
|
|
220
|
-
if (response.status === 404) {
|
|
221
|
-
return false;
|
|
222
|
-
}
|
|
223
|
-
if (!response.ok) {
|
|
224
|
-
throw await this.client.toError("has file", response);
|
|
225
|
-
}
|
|
226
|
-
return true;
|
|
227
|
-
}
|
|
228
|
-
/**
|
|
229
|
-
* @override
|
|
230
|
-
*/
|
|
231
|
-
async ensureBranch(branch, initialFile) {
|
|
232
|
-
const found = await this.client.request(
|
|
233
|
-
this.config,
|
|
234
|
-
`${this.repoPath()}/git/ref/heads/${this.encodePath(branch)}`,
|
|
235
|
-
{ method: "GET" }
|
|
236
|
-
);
|
|
237
|
-
if (found.ok) {
|
|
238
|
-
return;
|
|
239
|
-
}
|
|
240
|
-
if (found.status !== 404) {
|
|
241
|
-
throw await this.client.toError("get branch", found);
|
|
242
|
-
}
|
|
243
|
-
const treeSha = await this.postForSha("create tree", "/git/trees", {
|
|
244
|
-
tree: [
|
|
245
|
-
{
|
|
246
|
-
path: initialFile.path,
|
|
247
|
-
mode: "100644",
|
|
248
|
-
type: "blob",
|
|
249
|
-
content: initialFile.content
|
|
250
|
-
}
|
|
251
|
-
]
|
|
252
|
-
});
|
|
253
|
-
const commitSha = await this.postForSha("create commit", "/git/commits", {
|
|
254
|
-
message: `chore: \u521D\u59CB\u5316 ${branch} \u5206\u652F`,
|
|
255
|
-
tree: treeSha,
|
|
256
|
-
parents: []
|
|
257
|
-
});
|
|
258
|
-
const created = await this.client.request(
|
|
259
|
-
this.config,
|
|
260
|
-
`${this.repoPath()}/git/refs`,
|
|
261
|
-
{
|
|
262
|
-
method: "POST",
|
|
263
|
-
body: { ref: `refs/heads/${branch}`, sha: commitSha }
|
|
264
|
-
}
|
|
265
|
-
);
|
|
266
|
-
if (!created.ok && created.status !== 422) {
|
|
267
|
-
throw await this.client.toError("create branch", created);
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
/**
|
|
271
|
-
* @override
|
|
272
|
-
*/
|
|
273
|
-
async uploadFile(input) {
|
|
274
|
-
const response = await this.client.request(
|
|
275
|
-
this.config,
|
|
276
|
-
this.contentsPath(input.path),
|
|
277
|
-
{
|
|
278
|
-
method: "PUT",
|
|
279
|
-
body: {
|
|
280
|
-
message: input.message,
|
|
281
|
-
content: input.contentBase64,
|
|
282
|
-
branch: input.branch
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
);
|
|
286
|
-
if (response.ok) {
|
|
287
|
-
const json = await response.json();
|
|
288
|
-
return { url: this.requireHtmlUrl(json.content?.html_url, response) };
|
|
289
|
-
}
|
|
290
|
-
if (response.status === 422) {
|
|
291
|
-
return this.readExisting(input);
|
|
292
|
-
}
|
|
293
|
-
throw await this.client.toError("upload file", response);
|
|
294
|
-
}
|
|
295
|
-
async readExisting(input) {
|
|
296
|
-
const response = await this.client.request(
|
|
297
|
-
this.config,
|
|
298
|
-
`${this.contentsPath(input.path)}?ref=${encodeURIComponent(input.branch)}`,
|
|
299
|
-
{ method: "GET" }
|
|
300
|
-
);
|
|
301
|
-
if (!response.ok) {
|
|
302
|
-
throw await this.client.toError("upload file", response);
|
|
303
|
-
}
|
|
304
|
-
const json = await response.json();
|
|
305
|
-
return { url: this.requireHtmlUrl(json.html_url, response) };
|
|
306
|
-
}
|
|
307
|
-
async postForSha(stage, path, body) {
|
|
308
|
-
const response = await this.client.request(
|
|
309
|
-
this.config,
|
|
310
|
-
`${this.repoPath()}${path}`,
|
|
311
|
-
{ method: "POST", body }
|
|
312
|
-
);
|
|
313
|
-
if (!response.ok) {
|
|
314
|
-
throw await this.client.toError(stage, response);
|
|
315
|
-
}
|
|
316
|
-
const json = await response.json();
|
|
317
|
-
if (typeof json.sha !== "string" || !json.sha) {
|
|
318
|
-
throw new IssueForgeError(
|
|
319
|
-
`${stage}: unexpected response`,
|
|
320
|
-
response.status
|
|
321
|
-
);
|
|
322
|
-
}
|
|
323
|
-
return json.sha;
|
|
324
|
-
}
|
|
325
|
-
requireHtmlUrl(value, response) {
|
|
326
|
-
if (typeof value !== "string" || !value) {
|
|
327
|
-
throw new IssueForgeError(
|
|
328
|
-
"upload file: unexpected response",
|
|
329
|
-
response.status
|
|
330
|
-
);
|
|
331
|
-
}
|
|
332
|
-
return value;
|
|
333
|
-
}
|
|
334
|
-
contentsPath(path) {
|
|
335
|
-
return `${this.repoPath()}/contents/${this.encodePath(path)}`;
|
|
336
|
-
}
|
|
337
|
-
encodePath(path) {
|
|
338
|
-
return path.split("/").filter((segment) => segment.length > 0).map((segment) => encodeURIComponent(segment)).join("/");
|
|
339
|
-
}
|
|
340
|
-
repoPath() {
|
|
341
|
-
return `/repos/${encodeURIComponent(this.config.owner)}/${encodeURIComponent(this.config.repo)}`;
|
|
342
|
-
}
|
|
343
|
-
};
|
|
344
|
-
|
|
345
|
-
// src/github/GithubAppIssueForgeGateway.ts
|
|
346
|
-
var COMMENTS_PAGE_SIZE = 100;
|
|
347
|
-
var GithubAppIssueForgeGateway = class {
|
|
348
|
-
constructor(client, config) {
|
|
349
|
-
this.client = client;
|
|
350
|
-
this.config = config;
|
|
351
|
-
this.assets = new GithubAppRepoContentGateway(client, config);
|
|
352
|
-
}
|
|
353
|
-
assets;
|
|
354
|
-
/**
|
|
355
|
-
* @override
|
|
356
|
-
*/
|
|
357
|
-
async createIssue(input) {
|
|
358
|
-
const first = await this.postIssue(input, input.labels);
|
|
359
|
-
if (first.ok) {
|
|
360
|
-
return this.readCreated(first);
|
|
361
|
-
}
|
|
362
|
-
if (first.status === 422 && input.labels.length > 0) {
|
|
363
|
-
const retry = await this.postIssue(input, []);
|
|
364
|
-
if (retry.ok) {
|
|
365
|
-
return this.readCreated(retry);
|
|
366
|
-
}
|
|
367
|
-
throw await this.client.toError("create issue", retry);
|
|
368
|
-
}
|
|
369
|
-
throw await this.client.toError("create issue", first);
|
|
370
|
-
}
|
|
371
|
-
/**
|
|
372
|
-
* @override
|
|
373
|
-
*/
|
|
374
|
-
async createComment(issue, body) {
|
|
375
|
-
const response = await this.client.request(
|
|
376
|
-
this.config,
|
|
377
|
-
`${this.repoPath()}/issues/${String(issue.issueNumber)}/comments`,
|
|
378
|
-
{ method: "POST", body: { body } }
|
|
379
|
-
);
|
|
380
|
-
if (!response.ok) {
|
|
381
|
-
throw await this.client.toError("create comment", response);
|
|
382
|
-
}
|
|
383
|
-
}
|
|
384
|
-
/**
|
|
385
|
-
* @override
|
|
386
|
-
*/
|
|
387
|
-
async listComments(issue) {
|
|
388
|
-
const comments = [];
|
|
389
|
-
let page = 1;
|
|
390
|
-
for (; ; ) {
|
|
391
|
-
const response = await this.client.request(
|
|
392
|
-
this.config,
|
|
393
|
-
`${this.repoPath()}/issues/${String(issue.issueNumber)}/comments?per_page=${String(COMMENTS_PAGE_SIZE)}&page=${String(page)}`,
|
|
394
|
-
{ method: "GET" }
|
|
395
|
-
);
|
|
396
|
-
if (!response.ok) {
|
|
397
|
-
throw await this.client.toError("list comments", response);
|
|
398
|
-
}
|
|
399
|
-
const json = await response.json();
|
|
400
|
-
for (const item of json) {
|
|
401
|
-
if (typeof item.body === "string") {
|
|
402
|
-
comments.push({ body: item.body });
|
|
403
|
-
}
|
|
404
|
-
}
|
|
405
|
-
if (json.length < COMMENTS_PAGE_SIZE) {
|
|
406
|
-
break;
|
|
407
|
-
}
|
|
408
|
-
page += 1;
|
|
409
|
-
}
|
|
410
|
-
return comments;
|
|
411
|
-
}
|
|
412
|
-
/**
|
|
413
|
-
* @override
|
|
414
|
-
*/
|
|
415
|
-
async uploadAsset(input) {
|
|
416
|
-
const branch = input.branch?.trim() || "feedback-assets";
|
|
417
|
-
await this.assets.uploadFile({
|
|
418
|
-
path: input.path,
|
|
419
|
-
contentBase64: input.contentBase64,
|
|
420
|
-
branch,
|
|
421
|
-
message: input.message?.trim() || `chore(feedback): upload ${input.path}`
|
|
422
|
-
});
|
|
423
|
-
const encodedPath = input.path.split("/").filter((segment) => segment.length > 0).map((segment) => encodeURIComponent(segment)).join("/");
|
|
424
|
-
return {
|
|
425
|
-
url: `https://github.com/${encodeURIComponent(this.config.owner)}/${encodeURIComponent(this.config.repo)}/raw/${encodeURIComponent(branch)}/${encodedPath}`
|
|
426
|
-
};
|
|
427
|
-
}
|
|
428
|
-
postIssue(input, labels) {
|
|
429
|
-
return this.client.request(this.config, `${this.repoPath()}/issues`, {
|
|
430
|
-
method: "POST",
|
|
431
|
-
body: {
|
|
432
|
-
title: input.title,
|
|
433
|
-
body: input.body,
|
|
434
|
-
...labels.length > 0 ? { labels: [...labels] } : {}
|
|
435
|
-
}
|
|
436
|
-
});
|
|
437
|
-
}
|
|
438
|
-
async readCreated(response) {
|
|
439
|
-
const json = await response.json();
|
|
440
|
-
if (typeof json.number !== "number" || typeof json.html_url !== "string") {
|
|
441
|
-
throw new IssueForgeError(
|
|
442
|
-
"create issue: unexpected response",
|
|
443
|
-
response.status
|
|
444
|
-
);
|
|
445
|
-
}
|
|
446
|
-
return {
|
|
447
|
-
issueNumber: json.number,
|
|
448
|
-
issueUrl: json.html_url,
|
|
449
|
-
...typeof json.node_id === "string" ? { resourceKey: json.node_id } : {}
|
|
450
|
-
};
|
|
451
|
-
}
|
|
452
|
-
repoPath() {
|
|
453
|
-
return `/repos/${encodeURIComponent(this.config.owner)}/${encodeURIComponent(this.config.repo)}`;
|
|
454
|
-
}
|
|
455
|
-
};
|
|
456
|
-
|
|
457
|
-
// src/github/GithubWebhookVerifier.ts
|
|
458
|
-
var import_crypto = require("crypto");
|
|
459
|
-
var SIGNATURE_PREFIX = "sha256=";
|
|
460
|
-
var GithubWebhookVerifier = class {
|
|
461
|
-
constructor(secret) {
|
|
462
|
-
this.secret = secret;
|
|
463
|
-
}
|
|
464
|
-
/**
|
|
465
|
-
* @override
|
|
466
|
-
*/
|
|
467
|
-
async verify(rawBody, signatureHeader) {
|
|
468
|
-
if (signatureHeader == null || signatureHeader.trim() === "") {
|
|
469
|
-
return { ok: false, reason: "signature_header_missing" };
|
|
470
|
-
}
|
|
471
|
-
if (!signatureHeader.startsWith(SIGNATURE_PREFIX)) {
|
|
472
|
-
return { ok: false, reason: "signature_header_invalid" };
|
|
473
|
-
}
|
|
474
|
-
const secret = this.secret.trim();
|
|
475
|
-
if (!secret) {
|
|
476
|
-
return { ok: false, reason: "secret_not_configured" };
|
|
477
|
-
}
|
|
478
|
-
const expected = Buffer.from(
|
|
479
|
-
SIGNATURE_PREFIX + (0, import_crypto.createHmac)("sha256", secret).update(rawBody, "utf8").digest("hex"),
|
|
480
|
-
"utf8"
|
|
481
|
-
);
|
|
482
|
-
const received = Buffer.from(signatureHeader, "utf8");
|
|
483
|
-
if (expected.length !== received.length || !(0, import_crypto.timingSafeEqual)(expected, received)) {
|
|
484
|
-
return { ok: false, reason: "digest_mismatch" };
|
|
485
|
-
}
|
|
486
|
-
return { ok: true };
|
|
487
|
-
}
|
|
488
|
-
};
|
|
489
|
-
|
|
490
|
-
// src/github/createGithubAppForge.ts
|
|
491
|
-
function createGithubAppClient(options) {
|
|
492
|
-
return new GithubAppClient(options);
|
|
493
|
-
}
|
|
494
|
-
function createGithubAppIssueForge(client, config) {
|
|
495
|
-
return new GithubAppIssueForgeGateway(client, config);
|
|
496
|
-
}
|
|
497
|
-
function createGithubAppRepoContent(client, config) {
|
|
498
|
-
return new GithubAppRepoContentGateway(client, config);
|
|
499
|
-
}
|
|
500
|
-
function createGithubWebhookVerifier(secret) {
|
|
501
|
-
return new GithubWebhookVerifier(secret);
|
|
502
|
-
}
|
|
503
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
504
|
-
0 && (module.exports = {
|
|
505
|
-
GithubAppClient,
|
|
506
|
-
GithubAppIssueForgeGateway,
|
|
507
|
-
GithubAppRepoContentGateway,
|
|
508
|
-
GithubWebhookVerifier,
|
|
509
|
-
IssueForgeError,
|
|
510
|
-
createGithubAppClient,
|
|
511
|
-
createGithubAppIssueForge,
|
|
512
|
-
createGithubAppRepoContent,
|
|
513
|
-
createGithubWebhookVerifier
|
|
514
|
-
});
|
|
1
|
+
"use strict";var F=Object.create;var l=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var R=Object.getPrototypeOf,P=Object.prototype.hasOwnProperty;var E=(s,e)=>{for(var t in e)l(s,t,{get:e[t],enumerable:!0})},y=(s,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of G(e))!P.call(s,r)&&r!==t&&l(s,r,{get:()=>e[r],enumerable:!(o=k(e,r))||o.enumerable});return s};var _=(s,e,t)=>(t=s!=null?F(R(s)):{},y(e||!s||!s.__esModule?l(t,"default",{value:s,enumerable:!0}):t,s)),$=s=>y(l({},"__esModule",{value:!0}),s);var V={};E(V,{GithubAppClient:()=>c,GithubAppIssueForgeGateway:()=>u,GithubAppRepoContentGateway:()=>p,GithubWebhookVerifier:()=>h,IssueForgeError:()=>i,createGithubAppClient:()=>T,createGithubAppIssueForge:()=>w,createGithubAppRepoContent:()=>C,createGithubWebhookVerifier:()=>A});module.exports=$(V);var i=class extends Error{code="ISSUE_FORGE_FAILED";status;constructor(e,t){super(e),this.name="IssueForgeError",this.status=t}};var m=_(require("jsonwebtoken"),1);var d="https://api.github.com",U="2022-11-28",x="brain-toolkit-issue-forge",S=6e4,j=540,q=60,O=120*1e3,c=class{cache;userAgent;constructor(e){this.cache=e.cache,this.userAgent=e.userAgent?.trim()||x}async request(e,t,o){let r=await this.getInstallationToken(e),n=this.headers(`Bearer ${r}`);o.accept&&(n.Accept=o.accept),o.body!==void 0&&(n["Content-Type"]="application/json");let a=await this.send(`${d}${t}`,{method:o.method,headers:n,...o.body!==void 0?{body:JSON.stringify(o.body)}:{}});return(a.status===401||a.status===403)&&await this.cache.removeItem(this.tokenCacheKey(e)),a}async toError(e,t){let o="";try{let r=await t.json();o=typeof r.message=="string"?r.message:""}catch{o=""}return new i(`${e}: HTTP ${String(t.status)}${o?` ${o}`:""}`,t.status)}async getInstallationToken(e){let t=this.tokenCacheKey(e),o=await this.cache.getItem(t);if(o?.token)return o.token;let r=await this.send(`${d}/app/installations/${encodeURIComponent(e.installationId)}/access_tokens`,{method:"POST",headers:this.headers(`Bearer ${this.signAppJwt(e)}`)});if(!r.ok)throw await this.toError("installation token",r);let n=await r.json();if(typeof n.token!="string"||!n.token)throw new i("installation token: empty token",r.status);let a=typeof n.expires_at=="string"?Date.parse(n.expires_at):Number.NaN,g=Number.isFinite(a)?a-Date.now()-O:0;return g>0&&await this.cache.setItem(t,{token:n.token},{ttlMs:g}),n.token}signAppJwt(e){let t=Math.floor(Date.now()/1e3);try{return m.default.sign({iat:t-q,exp:t+j,iss:e.appId},this.normalizePrivateKey(e.privateKey),{algorithm:"RS256"})}catch(o){throw new i(`invalid GitHub App private key: ${o instanceof Error?o.message:String(o)}`,null)}}normalizePrivateKey(e){return e.replace(/\\n/g,`
|
|
2
|
+
`).replace(/\r\n/g,`
|
|
3
|
+
`).trim()}async send(e,t){try{return await fetch(e,{...t,signal:AbortSignal.timeout(S)})}catch(o){throw new i(`GitHub request failed: ${o instanceof Error?o.message:String(o)}`,null)}}headers(e){return{Accept:"application/vnd.github+json",Authorization:e,"User-Agent":this.userAgent,"X-GitHub-Api-Version":U}}tokenCacheKey(e){return`issue-forge:github:installation-token:${e.appId}:${e.installationId}`}};var W="application/vnd.github.raw+json",p=class{constructor(e,t){this.client=e;this.config=t}async readTextFile(e){let t=await this.client.request(this.config,this.contentsPath(e),{method:"GET",accept:W});if(t.status===404)return null;if(!t.ok)throw await this.client.toError("read file",t);return t.text()}async hasFile(e,t){let o=await this.client.request(this.config,`${this.contentsPath(e)}?ref=${encodeURIComponent(t)}`,{method:"GET"});if(o.status===404)return!1;if(!o.ok)throw await this.client.toError("has file",o);return!0}async ensureBranch(e,t){let o=await this.client.request(this.config,`${this.repoPath()}/git/ref/heads/${this.encodePath(e)}`,{method:"GET"});if(o.ok)return;if(o.status!==404)throw await this.client.toError("get branch",o);let r=await this.postForSha("create tree","/git/trees",{tree:[{path:t.path,mode:"100644",type:"blob",content:t.content}]}),n=await this.postForSha("create commit","/git/commits",{message:`chore: \u521D\u59CB\u5316 ${e} \u5206\u652F`,tree:r,parents:[]}),a=await this.client.request(this.config,`${this.repoPath()}/git/refs`,{method:"POST",body:{ref:`refs/heads/${e}`,sha:n}});if(!a.ok&&a.status!==422)throw await this.client.toError("create branch",a)}async uploadFile(e){let t=await this.client.request(this.config,this.contentsPath(e.path),{method:"PUT",body:{message:e.message,content:e.contentBase64,branch:e.branch}});if(t.ok){let o=await t.json();return{url:this.requireHtmlUrl(o.content?.html_url,t)}}if(t.status===422)return this.readExisting(e);throw await this.client.toError("upload file",t)}async readExisting(e){let t=await this.client.request(this.config,`${this.contentsPath(e.path)}?ref=${encodeURIComponent(e.branch)}`,{method:"GET"});if(!t.ok)throw await this.client.toError("upload file",t);let o=await t.json();return{url:this.requireHtmlUrl(o.html_url,t)}}async postForSha(e,t,o){let r=await this.client.request(this.config,`${this.repoPath()}${t}`,{method:"POST",body:o});if(!r.ok)throw await this.client.toError(e,r);let n=await r.json();if(typeof n.sha!="string"||!n.sha)throw new i(`${e}: unexpected response`,r.status);return n.sha}requireHtmlUrl(e,t){if(typeof e!="string"||!e)throw new i("upload file: unexpected response",t.status);return e}contentsPath(e){return`${this.repoPath()}/contents/${this.encodePath(e)}`}encodePath(e){return e.split("/").filter(t=>t.length>0).map(t=>encodeURIComponent(t)).join("/")}repoPath(){return`/repos/${encodeURIComponent(this.config.owner)}/${encodeURIComponent(this.config.repo)}`}};var I=100,u=class{constructor(e,t){this.client=e;this.config=t;this.assets=new p(e,t)}assets;async createIssue(e){let t=await this.postIssue(e,e.labels);if(t.ok)return this.readCreated(t);if(t.status===422&&e.labels.length>0){let o=await this.postIssue(e,[]);if(o.ok)return this.readCreated(o);throw await this.client.toError("create issue",o)}throw await this.client.toError("create issue",t)}async createComment(e,t){let o=await this.client.request(this.config,`${this.repoPath()}/issues/${String(e.issueNumber)}/comments`,{method:"POST",body:{body:t}});if(!o.ok)throw await this.client.toError("create comment",o)}async listComments(e){let t=[],o=1;for(;;){let r=await this.client.request(this.config,`${this.repoPath()}/issues/${String(e.issueNumber)}/comments?per_page=${String(I)}&page=${String(o)}`,{method:"GET"});if(!r.ok)throw await this.client.toError("list comments",r);let n=await r.json();for(let a of n)typeof a.body=="string"&&t.push({body:a.body});if(n.length<I)break;o+=1}return t}async uploadAsset(e){let t=e.branch?.trim()||"feedback-assets";await this.assets.uploadFile({path:e.path,contentBase64:e.contentBase64,branch:t,message:e.message?.trim()||`chore(feedback): upload ${e.path}`});let o=e.path.split("/").filter(r=>r.length>0).map(r=>encodeURIComponent(r)).join("/");return{url:`https://github.com/${encodeURIComponent(this.config.owner)}/${encodeURIComponent(this.config.repo)}/raw/${encodeURIComponent(t)}/${o}`}}postIssue(e,t){return this.client.request(this.config,`${this.repoPath()}/issues`,{method:"POST",body:{title:e.title,body:e.body,...t.length>0?{labels:[...t]}:{}}})}async readCreated(e){let t=await e.json();if(typeof t.number!="number"||typeof t.html_url!="string")throw new i("create issue: unexpected response",e.status);return{issueNumber:t.number,issueUrl:t.html_url,...typeof t.node_id=="string"?{resourceKey:t.node_id}:{}}}repoPath(){return`/repos/${encodeURIComponent(this.config.owner)}/${encodeURIComponent(this.config.repo)}`}};var f=require("crypto"),b="sha256=",h=class{constructor(e){this.secret=e}async verify(e,t){if(t==null||t.trim()==="")return{ok:!1,reason:"signature_header_missing"};if(!t.startsWith(b))return{ok:!1,reason:"signature_header_invalid"};let o=this.secret.trim();if(!o)return{ok:!1,reason:"secret_not_configured"};let r=Buffer.from(b+(0,f.createHmac)("sha256",o).update(e,"utf8").digest("hex"),"utf8"),n=Buffer.from(t,"utf8");return r.length!==n.length||!(0,f.timingSafeEqual)(r,n)?{ok:!1,reason:"digest_mismatch"}:{ok:!0}}};function T(s){return new c(s)}function w(s,e){return new u(s,e)}function C(s,e){return new p(s,e)}function A(s){return new h(s)}0&&(module.exports={GithubAppClient,GithubAppIssueForgeGateway,GithubAppRepoContentGateway,GithubWebhookVerifier,IssueForgeError,createGithubAppClient,createGithubAppIssueForge,createGithubAppRepoContent,createGithubWebhookVerifier});
|
|
515
4
|
//# sourceMappingURL=index.cjs.map
|