@brain-toolkit/issue-forge 0.0.0-stage → 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ - 初版:GitHub App Issue 网关 + `/feedback` 同步编排(建 Issue、截图评论、webhook 关单回写)
package/README.md CHANGED
@@ -1,3 +1,44 @@
1
- # Temporary Holding Version
1
+ # @brain-toolkit/issue-forge
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Forge 无关的 Issue 网关;**GitHub App** 为第一个实现。可选子路径 **`/feedback`** 提供「反馈 → Issue」编排。
4
+
5
+ ## 构建与发布
6
+
7
+ ```bash
8
+ pnpm --filter @brain-toolkit/issue-forge build
9
+ ```
10
+
11
+ - monorepo 内:`exports` 指向 `src`(与 `workspace:*` 一致)
12
+ - npm 发布:`publishConfig` 指向 `dist`(esm / cjs / dts)
13
+
14
+ ## `@brain-toolkit/issue-forge`(协议)
15
+
16
+ ```ts
17
+ import {
18
+ createGithubAppClient,
19
+ createGithubAppIssueForge
20
+ } from '@brain-toolkit/issue-forge';
21
+
22
+ const client = createGithubAppClient({ cache });
23
+ const forge = createGithubAppIssueForge(client, authConfig);
24
+ await forge.createIssue({ title, body, labels: ['feedback'] });
25
+ ```
26
+
27
+ ## `@brain-toolkit/issue-forge/feedback`
28
+
29
+ 包只做两件事:**拉模板** + **`{{var}}` 替换**。业务字段、文案、语种由应用在 Host 里组装 `variables`。
30
+
31
+ ```ts
32
+ import { createGithubFeedbackIssueBundle } from '@brain-toolkit/issue-forge/feedback';
33
+
34
+ const bundle = createGithubFeedbackIssueBundle({
35
+ host, // resolveIssueContent → { variables, labels, issueNumber }
36
+ client,
37
+ cache,
38
+ defaultTemplate // 可选回退模板;语言写在模板里
39
+ });
40
+
41
+ await bundle.sync.syncFeedback(id);
42
+ ```
43
+
44
+ 应用(如 PAM)一个 Bundle:实现 Host、传入模板、兼 webhook 验签。
@@ -0,0 +1,103 @@
1
+ /**
2
+ * 创建 Issue 的归一入参(平台标签语义由实现消化)。
3
+ */
4
+ type ForgeIssueCreateInputType = {
5
+ readonly title: string;
6
+ readonly body: string;
7
+ /** 如 `feedback`、`type:bug`;目标平台无标签时实现可忽略或降级重试 */
8
+ readonly labels: readonly string[];
9
+ };
10
+ /**
11
+ * 创建成功后的归一结果。
12
+ */
13
+ type ForgeIssueCreatedType = {
14
+ readonly issueNumber: number;
15
+ readonly issueUrl: string;
16
+ /** 平台侧稳定 id(如 GitHub node_id),可选 */
17
+ readonly resourceKey?: string;
18
+ };
19
+ /**
20
+ * 评论 / 附件所指向的 Issue 引用。
21
+ */
22
+ type ForgeIssueRefType = {
23
+ readonly issueNumber: number;
24
+ readonly resourceKey?: string;
25
+ };
26
+ /**
27
+ * 可选资源上传(截图等);不能上传的平台可不实现 `uploadAsset`。
28
+ */
29
+ type ForgeAssetUploadInputType = {
30
+ readonly path: string;
31
+ readonly contentBase64: string;
32
+ readonly message?: string;
33
+ /** 实现可解释为分支名等;GitHub 用独立 assets 分支 */
34
+ readonly branch?: string;
35
+ };
36
+ type ForgeAssetUploadedType = {
37
+ /** Issue 可引用的展示 / raw URL */
38
+ readonly url: string;
39
+ };
40
+ /**
41
+ * GitHub App 专用鉴权;其它平台另建 `*AuthConfigType`,不进通用 Interface。
42
+ */
43
+ type GithubAppAuthConfigType = {
44
+ readonly appId: string;
45
+ readonly installationId: string;
46
+ readonly privateKey: string;
47
+ readonly owner: string;
48
+ readonly repo: string;
49
+ };
50
+ /**
51
+ * installation token 缓存(应用注入 MemoryKv / Redis 等)。
52
+ */
53
+ interface IssueForgeTokenCacheInterface {
54
+ getItem<T>(key: string): Promise<T | null | undefined>;
55
+ setItem<T>(key: string, value: T, options?: {
56
+ readonly ttlMs?: number;
57
+ }): Promise<unknown>;
58
+ removeItem(key: string): Promise<unknown>;
59
+ }
60
+ type IssueWebhookVerifyResultType = {
61
+ readonly ok: true;
62
+ } | {
63
+ readonly ok: false;
64
+ readonly reason: string;
65
+ };
66
+
67
+ /**
68
+ * Forge API 调用失败(换票、建 Issue、上传等)。
69
+ */
70
+ declare class IssueForgeError extends Error {
71
+ readonly code: "ISSUE_FORGE_FAILED";
72
+ /** HTTP 状态码;网络错误等无响应时为 null */
73
+ readonly status: number | null;
74
+ constructor(message: string, status: number | null);
75
+ }
76
+
77
+ type GithubAppRequestType = {
78
+ readonly method: 'GET' | 'POST' | 'PUT' | 'PATCH';
79
+ readonly body?: unknown;
80
+ readonly accept?: string;
81
+ };
82
+ type GithubAppClientOptionsType = {
83
+ readonly cache: IssueForgeTokenCacheInterface;
84
+ readonly userAgent?: string;
85
+ };
86
+ /**
87
+ * 以 GitHub App installation 身份调用 REST API(低层;config 仍按次传入以便多仓复用同一 client)。
88
+ */
89
+ declare class GithubAppClient {
90
+ protected readonly cache: IssueForgeTokenCacheInterface;
91
+ protected readonly userAgent: string;
92
+ constructor(options: GithubAppClientOptionsType);
93
+ request(config: GithubAppAuthConfigType, path: string, init: GithubAppRequestType): Promise<Response>;
94
+ toError(stage: string, response: Response): Promise<IssueForgeError>;
95
+ protected getInstallationToken(config: GithubAppAuthConfigType): Promise<string>;
96
+ protected signAppJwt(config: GithubAppAuthConfigType): string;
97
+ protected normalizePrivateKey(raw: string): string;
98
+ protected send(url: string, init: RequestInit): Promise<Response>;
99
+ protected headers(authorization: string): Record<string, string>;
100
+ protected tokenCacheKey(config: GithubAppAuthConfigType): string;
101
+ }
102
+
103
+ export { type ForgeIssueCreateInputType as F, GithubAppClient as G, type IssueWebhookVerifyResultType as I, type ForgeIssueCreatedType as a, type ForgeIssueRefType as b, type ForgeAssetUploadInputType as c, type ForgeAssetUploadedType as d, type GithubAppAuthConfigType as e, type IssueForgeTokenCacheInterface as f, IssueForgeError as g, type GithubAppClientOptionsType as h, type GithubAppRequestType as i };
@@ -0,0 +1,471 @@
1
+ // src/errors/IssueForgeError.ts
2
+ var IssueForgeError = class extends Error {
3
+ code = "ISSUE_FORGE_FAILED";
4
+ /** HTTP 状态码;网络错误等无响应时为 null */
5
+ status;
6
+ constructor(message, status) {
7
+ super(message);
8
+ this.name = "IssueForgeError";
9
+ this.status = status;
10
+ }
11
+ };
12
+
13
+ // src/github/GithubAppClient.ts
14
+ import jwt from "jsonwebtoken";
15
+ var GITHUB_API = "https://api.github.com";
16
+ var GITHUB_API_VERSION = "2022-11-28";
17
+ var DEFAULT_USER_AGENT = "brain-toolkit-issue-forge";
18
+ var REQUEST_TIMEOUT_MS = 6e4;
19
+ var APP_JWT_TTL_SEC = 9 * 60;
20
+ var APP_JWT_CLOCK_SKEW_SEC = 60;
21
+ var TOKEN_REFRESH_MARGIN_MS = 2 * 60 * 1e3;
22
+ var GithubAppClient = class {
23
+ cache;
24
+ userAgent;
25
+ constructor(options) {
26
+ this.cache = options.cache;
27
+ this.userAgent = options.userAgent?.trim() || DEFAULT_USER_AGENT;
28
+ }
29
+ async request(config, path, init) {
30
+ const token = await this.getInstallationToken(config);
31
+ const headers = this.headers(`Bearer ${token}`);
32
+ if (init.accept) {
33
+ headers.Accept = init.accept;
34
+ }
35
+ if (init.body !== void 0) {
36
+ headers["Content-Type"] = "application/json";
37
+ }
38
+ const response = await this.send(`${GITHUB_API}${path}`, {
39
+ method: init.method,
40
+ headers,
41
+ ...init.body !== void 0 ? { body: JSON.stringify(init.body) } : {}
42
+ });
43
+ if (response.status === 401 || response.status === 403) {
44
+ await this.cache.removeItem(this.tokenCacheKey(config));
45
+ }
46
+ return response;
47
+ }
48
+ async toError(stage, response) {
49
+ let detail = "";
50
+ try {
51
+ const json = await response.json();
52
+ detail = typeof json.message === "string" ? json.message : "";
53
+ } catch {
54
+ detail = "";
55
+ }
56
+ return new IssueForgeError(
57
+ `${stage}: HTTP ${String(response.status)}${detail ? ` ${detail}` : ""}`,
58
+ response.status
59
+ );
60
+ }
61
+ async getInstallationToken(config) {
62
+ const cacheKey = this.tokenCacheKey(config);
63
+ const cached = await this.cache.getItem(cacheKey);
64
+ if (cached?.token) {
65
+ return cached.token;
66
+ }
67
+ const response = await this.send(
68
+ `${GITHUB_API}/app/installations/${encodeURIComponent(config.installationId)}/access_tokens`,
69
+ {
70
+ method: "POST",
71
+ headers: this.headers(`Bearer ${this.signAppJwt(config)}`)
72
+ }
73
+ );
74
+ if (!response.ok) {
75
+ throw await this.toError("installation token", response);
76
+ }
77
+ const json = await response.json();
78
+ if (typeof json.token !== "string" || !json.token) {
79
+ throw new IssueForgeError(
80
+ "installation token: empty token",
81
+ response.status
82
+ );
83
+ }
84
+ const expiresAtMs = typeof json.expires_at === "string" ? Date.parse(json.expires_at) : Number.NaN;
85
+ const ttlMs = Number.isFinite(expiresAtMs) ? expiresAtMs - Date.now() - TOKEN_REFRESH_MARGIN_MS : 0;
86
+ if (ttlMs > 0) {
87
+ await this.cache.setItem(
88
+ cacheKey,
89
+ { token: json.token },
90
+ { ttlMs }
91
+ );
92
+ }
93
+ return json.token;
94
+ }
95
+ signAppJwt(config) {
96
+ const nowSec = Math.floor(Date.now() / 1e3);
97
+ try {
98
+ return jwt.sign(
99
+ {
100
+ iat: nowSec - APP_JWT_CLOCK_SKEW_SEC,
101
+ exp: nowSec + APP_JWT_TTL_SEC,
102
+ iss: config.appId
103
+ },
104
+ this.normalizePrivateKey(config.privateKey),
105
+ { algorithm: "RS256" }
106
+ );
107
+ } catch (error) {
108
+ throw new IssueForgeError(
109
+ `invalid GitHub App private key: ${error instanceof Error ? error.message : String(error)}`,
110
+ null
111
+ );
112
+ }
113
+ }
114
+ normalizePrivateKey(raw) {
115
+ return raw.replace(/\\n/g, "\n").replace(/\r\n/g, "\n").trim();
116
+ }
117
+ async send(url, init) {
118
+ try {
119
+ return await fetch(url, {
120
+ ...init,
121
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
122
+ });
123
+ } catch (error) {
124
+ throw new IssueForgeError(
125
+ `GitHub request failed: ${error instanceof Error ? error.message : String(error)}`,
126
+ null
127
+ );
128
+ }
129
+ }
130
+ headers(authorization) {
131
+ return {
132
+ Accept: "application/vnd.github+json",
133
+ Authorization: authorization,
134
+ "User-Agent": this.userAgent,
135
+ "X-GitHub-Api-Version": GITHUB_API_VERSION
136
+ };
137
+ }
138
+ tokenCacheKey(config) {
139
+ return `issue-forge:github:installation-token:${config.appId}:${config.installationId}`;
140
+ }
141
+ };
142
+
143
+ // src/github/GithubAppRepoContentGateway.ts
144
+ var ACCEPT_RAW = "application/vnd.github.raw+json";
145
+ var GithubAppRepoContentGateway = class {
146
+ constructor(client, config) {
147
+ this.client = client;
148
+ this.config = config;
149
+ }
150
+ /**
151
+ * @override
152
+ */
153
+ async readTextFile(path) {
154
+ const response = await this.client.request(
155
+ this.config,
156
+ this.contentsPath(path),
157
+ { method: "GET", accept: ACCEPT_RAW }
158
+ );
159
+ if (response.status === 404) {
160
+ return null;
161
+ }
162
+ if (!response.ok) {
163
+ throw await this.client.toError("read file", response);
164
+ }
165
+ return response.text();
166
+ }
167
+ /**
168
+ * @override
169
+ */
170
+ async hasFile(path, branch) {
171
+ const response = await this.client.request(
172
+ this.config,
173
+ `${this.contentsPath(path)}?ref=${encodeURIComponent(branch)}`,
174
+ { method: "GET" }
175
+ );
176
+ if (response.status === 404) {
177
+ return false;
178
+ }
179
+ if (!response.ok) {
180
+ throw await this.client.toError("has file", response);
181
+ }
182
+ return true;
183
+ }
184
+ /**
185
+ * @override
186
+ */
187
+ async ensureBranch(branch, initialFile) {
188
+ const found = await this.client.request(
189
+ this.config,
190
+ `${this.repoPath()}/git/ref/heads/${this.encodePath(branch)}`,
191
+ { method: "GET" }
192
+ );
193
+ if (found.ok) {
194
+ return;
195
+ }
196
+ if (found.status !== 404) {
197
+ throw await this.client.toError("get branch", found);
198
+ }
199
+ const treeSha = await this.postForSha("create tree", "/git/trees", {
200
+ tree: [
201
+ {
202
+ path: initialFile.path,
203
+ mode: "100644",
204
+ type: "blob",
205
+ content: initialFile.content
206
+ }
207
+ ]
208
+ });
209
+ const commitSha = await this.postForSha("create commit", "/git/commits", {
210
+ message: `chore: \u521D\u59CB\u5316 ${branch} \u5206\u652F`,
211
+ tree: treeSha,
212
+ parents: []
213
+ });
214
+ const created = await this.client.request(
215
+ this.config,
216
+ `${this.repoPath()}/git/refs`,
217
+ {
218
+ method: "POST",
219
+ body: { ref: `refs/heads/${branch}`, sha: commitSha }
220
+ }
221
+ );
222
+ if (!created.ok && created.status !== 422) {
223
+ throw await this.client.toError("create branch", created);
224
+ }
225
+ }
226
+ /**
227
+ * @override
228
+ */
229
+ async uploadFile(input) {
230
+ const response = await this.client.request(
231
+ this.config,
232
+ this.contentsPath(input.path),
233
+ {
234
+ method: "PUT",
235
+ body: {
236
+ message: input.message,
237
+ content: input.contentBase64,
238
+ branch: input.branch
239
+ }
240
+ }
241
+ );
242
+ if (response.ok) {
243
+ const json = await response.json();
244
+ return { url: this.requireHtmlUrl(json.content?.html_url, response) };
245
+ }
246
+ if (response.status === 422) {
247
+ return this.readExisting(input);
248
+ }
249
+ throw await this.client.toError("upload file", response);
250
+ }
251
+ async readExisting(input) {
252
+ const response = await this.client.request(
253
+ this.config,
254
+ `${this.contentsPath(input.path)}?ref=${encodeURIComponent(input.branch)}`,
255
+ { method: "GET" }
256
+ );
257
+ if (!response.ok) {
258
+ throw await this.client.toError("upload file", response);
259
+ }
260
+ const json = await response.json();
261
+ return { url: this.requireHtmlUrl(json.html_url, response) };
262
+ }
263
+ async postForSha(stage, path, body) {
264
+ const response = await this.client.request(
265
+ this.config,
266
+ `${this.repoPath()}${path}`,
267
+ { method: "POST", body }
268
+ );
269
+ if (!response.ok) {
270
+ throw await this.client.toError(stage, response);
271
+ }
272
+ const json = await response.json();
273
+ if (typeof json.sha !== "string" || !json.sha) {
274
+ throw new IssueForgeError(
275
+ `${stage}: unexpected response`,
276
+ response.status
277
+ );
278
+ }
279
+ return json.sha;
280
+ }
281
+ requireHtmlUrl(value, response) {
282
+ if (typeof value !== "string" || !value) {
283
+ throw new IssueForgeError(
284
+ "upload file: unexpected response",
285
+ response.status
286
+ );
287
+ }
288
+ return value;
289
+ }
290
+ contentsPath(path) {
291
+ return `${this.repoPath()}/contents/${this.encodePath(path)}`;
292
+ }
293
+ encodePath(path) {
294
+ return path.split("/").filter((segment) => segment.length > 0).map((segment) => encodeURIComponent(segment)).join("/");
295
+ }
296
+ repoPath() {
297
+ return `/repos/${encodeURIComponent(this.config.owner)}/${encodeURIComponent(this.config.repo)}`;
298
+ }
299
+ };
300
+
301
+ // src/github/GithubAppIssueForgeGateway.ts
302
+ var COMMENTS_PAGE_SIZE = 100;
303
+ var GithubAppIssueForgeGateway = class {
304
+ constructor(client, config) {
305
+ this.client = client;
306
+ this.config = config;
307
+ this.assets = new GithubAppRepoContentGateway(client, config);
308
+ }
309
+ assets;
310
+ /**
311
+ * @override
312
+ */
313
+ async createIssue(input) {
314
+ const first = await this.postIssue(input, input.labels);
315
+ if (first.ok) {
316
+ return this.readCreated(first);
317
+ }
318
+ if (first.status === 422 && input.labels.length > 0) {
319
+ const retry = await this.postIssue(input, []);
320
+ if (retry.ok) {
321
+ return this.readCreated(retry);
322
+ }
323
+ throw await this.client.toError("create issue", retry);
324
+ }
325
+ throw await this.client.toError("create issue", first);
326
+ }
327
+ /**
328
+ * @override
329
+ */
330
+ async createComment(issue, body) {
331
+ const response = await this.client.request(
332
+ this.config,
333
+ `${this.repoPath()}/issues/${String(issue.issueNumber)}/comments`,
334
+ { method: "POST", body: { body } }
335
+ );
336
+ if (!response.ok) {
337
+ throw await this.client.toError("create comment", response);
338
+ }
339
+ }
340
+ /**
341
+ * @override
342
+ */
343
+ async listComments(issue) {
344
+ const comments = [];
345
+ let page = 1;
346
+ for (; ; ) {
347
+ const response = await this.client.request(
348
+ this.config,
349
+ `${this.repoPath()}/issues/${String(issue.issueNumber)}/comments?per_page=${String(COMMENTS_PAGE_SIZE)}&page=${String(page)}`,
350
+ { method: "GET" }
351
+ );
352
+ if (!response.ok) {
353
+ throw await this.client.toError("list comments", response);
354
+ }
355
+ const json = await response.json();
356
+ for (const item of json) {
357
+ if (typeof item.body === "string") {
358
+ comments.push({ body: item.body });
359
+ }
360
+ }
361
+ if (json.length < COMMENTS_PAGE_SIZE) {
362
+ break;
363
+ }
364
+ page += 1;
365
+ }
366
+ return comments;
367
+ }
368
+ /**
369
+ * @override
370
+ */
371
+ async uploadAsset(input) {
372
+ const branch = input.branch?.trim() || "feedback-assets";
373
+ await this.assets.uploadFile({
374
+ path: input.path,
375
+ contentBase64: input.contentBase64,
376
+ branch,
377
+ message: input.message?.trim() || `chore(feedback): upload ${input.path}`
378
+ });
379
+ const encodedPath = input.path.split("/").filter((segment) => segment.length > 0).map((segment) => encodeURIComponent(segment)).join("/");
380
+ return {
381
+ url: `https://github.com/${encodeURIComponent(this.config.owner)}/${encodeURIComponent(this.config.repo)}/raw/${encodeURIComponent(branch)}/${encodedPath}`
382
+ };
383
+ }
384
+ postIssue(input, labels) {
385
+ return this.client.request(this.config, `${this.repoPath()}/issues`, {
386
+ method: "POST",
387
+ body: {
388
+ title: input.title,
389
+ body: input.body,
390
+ ...labels.length > 0 ? { labels: [...labels] } : {}
391
+ }
392
+ });
393
+ }
394
+ async readCreated(response) {
395
+ const json = await response.json();
396
+ if (typeof json.number !== "number" || typeof json.html_url !== "string") {
397
+ throw new IssueForgeError(
398
+ "create issue: unexpected response",
399
+ response.status
400
+ );
401
+ }
402
+ return {
403
+ issueNumber: json.number,
404
+ issueUrl: json.html_url,
405
+ ...typeof json.node_id === "string" ? { resourceKey: json.node_id } : {}
406
+ };
407
+ }
408
+ repoPath() {
409
+ return `/repos/${encodeURIComponent(this.config.owner)}/${encodeURIComponent(this.config.repo)}`;
410
+ }
411
+ };
412
+
413
+ // src/github/GithubWebhookVerifier.ts
414
+ import { createHmac, timingSafeEqual } from "crypto";
415
+ var SIGNATURE_PREFIX = "sha256=";
416
+ var GithubWebhookVerifier = class {
417
+ constructor(secret) {
418
+ this.secret = secret;
419
+ }
420
+ /**
421
+ * @override
422
+ */
423
+ async verify(rawBody, signatureHeader) {
424
+ if (signatureHeader == null || signatureHeader.trim() === "") {
425
+ return { ok: false, reason: "signature_header_missing" };
426
+ }
427
+ if (!signatureHeader.startsWith(SIGNATURE_PREFIX)) {
428
+ return { ok: false, reason: "signature_header_invalid" };
429
+ }
430
+ const secret = this.secret.trim();
431
+ if (!secret) {
432
+ return { ok: false, reason: "secret_not_configured" };
433
+ }
434
+ const expected = Buffer.from(
435
+ SIGNATURE_PREFIX + createHmac("sha256", secret).update(rawBody, "utf8").digest("hex"),
436
+ "utf8"
437
+ );
438
+ const received = Buffer.from(signatureHeader, "utf8");
439
+ if (expected.length !== received.length || !timingSafeEqual(expected, received)) {
440
+ return { ok: false, reason: "digest_mismatch" };
441
+ }
442
+ return { ok: true };
443
+ }
444
+ };
445
+
446
+ // src/github/createGithubAppForge.ts
447
+ function createGithubAppClient(options) {
448
+ return new GithubAppClient(options);
449
+ }
450
+ function createGithubAppIssueForge(client, config) {
451
+ return new GithubAppIssueForgeGateway(client, config);
452
+ }
453
+ function createGithubAppRepoContent(client, config) {
454
+ return new GithubAppRepoContentGateway(client, config);
455
+ }
456
+ function createGithubWebhookVerifier(secret) {
457
+ return new GithubWebhookVerifier(secret);
458
+ }
459
+
460
+ export {
461
+ IssueForgeError,
462
+ GithubAppClient,
463
+ GithubAppRepoContentGateway,
464
+ GithubAppIssueForgeGateway,
465
+ GithubWebhookVerifier,
466
+ createGithubAppClient,
467
+ createGithubAppIssueForge,
468
+ createGithubAppRepoContent,
469
+ createGithubWebhookVerifier
470
+ };
471
+ //# sourceMappingURL=chunk-RQKDVDLH.js.map