@memberjunction/core-actions 6.2.1 → 6.3.0-edge.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.
Files changed (131) hide show
  1. package/README.md +28 -2
  2. package/dist/custom/ai/base-find-skills.action.d.ts +56 -0
  3. package/dist/custom/ai/base-find-skills.action.d.ts.map +1 -0
  4. package/dist/custom/ai/base-find-skills.action.js +237 -0
  5. package/dist/custom/ai/base-find-skills.action.js.map +1 -0
  6. package/dist/custom/ai/configure-agent-user-policy.action.d.ts.map +1 -1
  7. package/dist/custom/ai/configure-agent-user-policy.action.js +96 -15
  8. package/dist/custom/ai/configure-agent-user-policy.action.js.map +1 -1
  9. package/dist/custom/ai/find-best-skill.action.d.ts +13 -0
  10. package/dist/custom/ai/find-best-skill.action.d.ts.map +1 -0
  11. package/dist/custom/ai/find-best-skill.action.js +29 -0
  12. package/dist/custom/ai/find-best-skill.action.js.map +1 -0
  13. package/dist/custom/ai/find-candidate-skills.action.d.ts +21 -0
  14. package/dist/custom/ai/find-candidate-skills.action.d.ts.map +1 -0
  15. package/dist/custom/ai/find-candidate-skills.action.js +35 -0
  16. package/dist/custom/ai/find-candidate-skills.action.js.map +1 -0
  17. package/dist/custom/ai/get-skill-details.action.d.ts +40 -0
  18. package/dist/custom/ai/get-skill-details.action.d.ts.map +1 -0
  19. package/dist/custom/ai/get-skill-details.action.js +133 -0
  20. package/dist/custom/ai/get-skill-details.action.js.map +1 -0
  21. package/dist/custom/ai/prepare-outbound-call-brief.action.d.ts.map +1 -1
  22. package/dist/custom/ai/prepare-outbound-call-brief.action.js +10 -1
  23. package/dist/custom/ai/prepare-outbound-call-brief.action.js.map +1 -1
  24. package/dist/custom/ai/schedule-next-agent-wake.action.d.ts +16 -0
  25. package/dist/custom/ai/schedule-next-agent-wake.action.d.ts.map +1 -1
  26. package/dist/custom/ai/schedule-next-agent-wake.action.js +100 -17
  27. package/dist/custom/ai/schedule-next-agent-wake.action.js.map +1 -1
  28. package/dist/custom/ai/semantic-entity-search.helper.d.ts +1 -1
  29. package/dist/custom/ai/semantic-entity-search.helper.d.ts.map +1 -1
  30. package/dist/custom/ai/send-inter-agent-request.action.d.ts +17 -6
  31. package/dist/custom/ai/send-inter-agent-request.action.d.ts.map +1 -1
  32. package/dist/custom/ai/send-inter-agent-request.action.js +227 -29
  33. package/dist/custom/ai/send-inter-agent-request.action.js.map +1 -1
  34. package/dist/custom/ai/trigger-agent-wake.action.d.ts +19 -0
  35. package/dist/custom/ai/trigger-agent-wake.action.d.ts.map +1 -0
  36. package/dist/custom/ai/trigger-agent-wake.action.js +134 -0
  37. package/dist/custom/ai/trigger-agent-wake.action.js.map +1 -0
  38. package/dist/custom/ai/user-scoped-communication.action.d.ts +1 -1
  39. package/dist/custom/ai/user-scoped-communication.action.d.ts.map +1 -1
  40. package/dist/custom/ai/user-scoped-communication.action.js +13 -7
  41. package/dist/custom/ai/user-scoped-communication.action.js.map +1 -1
  42. package/dist/custom/communication/teams-webhook.action.d.ts +5 -0
  43. package/dist/custom/communication/teams-webhook.action.d.ts.map +1 -1
  44. package/dist/custom/communication/teams-webhook.action.js +15 -1
  45. package/dist/custom/communication/teams-webhook.action.js.map +1 -1
  46. package/dist/custom/crud/agent-data-policy-guard.d.ts +155 -0
  47. package/dist/custom/crud/agent-data-policy-guard.d.ts.map +1 -0
  48. package/dist/custom/crud/agent-data-policy-guard.js +898 -0
  49. package/dist/custom/crud/agent-data-policy-guard.js.map +1 -0
  50. package/dist/custom/crud/create-record.action.d.ts.map +1 -1
  51. package/dist/custom/crud/create-record.action.js +25 -0
  52. package/dist/custom/crud/create-record.action.js.map +1 -1
  53. package/dist/custom/crud/delete-record.action.d.ts.map +1 -1
  54. package/dist/custom/crud/delete-record.action.js +36 -1
  55. package/dist/custom/crud/delete-record.action.js.map +1 -1
  56. package/dist/custom/crud/get-record.action.d.ts.map +1 -1
  57. package/dist/custom/crud/get-record.action.js +36 -1
  58. package/dist/custom/crud/get-record.action.js.map +1 -1
  59. package/dist/custom/crud/get-records.action.d.ts +3 -3
  60. package/dist/custom/crud/get-records.action.d.ts.map +1 -1
  61. package/dist/custom/crud/get-records.action.js +55 -6
  62. package/dist/custom/crud/get-records.action.js.map +1 -1
  63. package/dist/custom/crud/update-record.action.d.ts.map +1 -1
  64. package/dist/custom/crud/update-record.action.js +82 -0
  65. package/dist/custom/crud/update-record.action.js.map +1 -1
  66. package/dist/custom/crud/write-entity-fields.action.d.ts.map +1 -1
  67. package/dist/custom/crud/write-entity-fields.action.js +73 -0
  68. package/dist/custom/crud/write-entity-fields.action.js.map +1 -1
  69. package/dist/custom/data/get-entity-details.action.d.ts.map +1 -1
  70. package/dist/custom/data/get-entity-details.action.js +33 -2
  71. package/dist/custom/data/get-entity-details.action.js.map +1 -1
  72. package/dist/custom/data/get-graph-context.action.d.ts +39 -0
  73. package/dist/custom/data/get-graph-context.action.d.ts.map +1 -0
  74. package/dist/custom/data/get-graph-context.action.js +303 -0
  75. package/dist/custom/data/get-graph-context.action.js.map +1 -0
  76. package/dist/custom/data/run-adhoc-query.action.d.ts.map +1 -1
  77. package/dist/custom/data/run-adhoc-query.action.js +6 -1
  78. package/dist/custom/data/run-adhoc-query.action.js.map +1 -1
  79. package/dist/custom/data/run-stored-query.action.d.ts.map +1 -1
  80. package/dist/custom/data/run-stored-query.action.js +8 -2
  81. package/dist/custom/data/run-stored-query.action.js.map +1 -1
  82. package/dist/custom/github/base-github.action.d.ts +51 -0
  83. package/dist/custom/github/base-github.action.d.ts.map +1 -0
  84. package/dist/custom/github/base-github.action.js +220 -0
  85. package/dist/custom/github/base-github.action.js.map +1 -0
  86. package/dist/custom/github/github-actions.d.ts +66 -0
  87. package/dist/custom/github/github-actions.d.ts.map +1 -0
  88. package/dist/custom/github/github-actions.js +715 -0
  89. package/dist/custom/github/github-actions.js.map +1 -0
  90. package/dist/custom/github/github-app-auth.d.ts +122 -0
  91. package/dist/custom/github/github-app-auth.d.ts.map +1 -0
  92. package/dist/custom/github/github-app-auth.js +396 -0
  93. package/dist/custom/github/github-app-auth.js.map +1 -0
  94. package/dist/custom/github/github-client.d.ts +288 -0
  95. package/dist/custom/github/github-client.d.ts.map +1 -0
  96. package/dist/custom/github/github-client.js +891 -0
  97. package/dist/custom/github/github-client.js.map +1 -0
  98. package/dist/custom/github/github-credential-resolver.d.ts +73 -0
  99. package/dist/custom/github/github-credential-resolver.d.ts.map +1 -0
  100. package/dist/custom/github/github-credential-resolver.js +330 -0
  101. package/dist/custom/github/github-credential-resolver.js.map +1 -0
  102. package/dist/custom/github/github-types.d.ts +216 -0
  103. package/dist/custom/github/github-types.d.ts.map +1 -0
  104. package/dist/custom/github/github-types.js +11 -0
  105. package/dist/custom/github/github-types.js.map +1 -0
  106. package/dist/custom/github/index.d.ts +7 -0
  107. package/dist/custom/github/index.d.ts.map +1 -0
  108. package/dist/custom/github/index.js +7 -0
  109. package/dist/custom/github/index.js.map +1 -0
  110. package/dist/custom/utilities/docx-renderer.d.ts.map +1 -1
  111. package/dist/custom/utilities/docx-renderer.js +29 -6
  112. package/dist/custom/utilities/docx-renderer.js.map +1 -1
  113. package/dist/custom/visualization/create-svg-network.action.js +1 -1
  114. package/dist/custom/visualization/create-svg-network.action.js.map +1 -1
  115. package/dist/custom/visualization/create-svg-sketch-diagram.action.js +3 -3
  116. package/dist/custom/visualization/create-svg-sketch-diagram.action.js.map +1 -1
  117. package/dist/custom/visualization/shared/svg-utils.d.ts +23 -5
  118. package/dist/custom/visualization/shared/svg-utils.d.ts.map +1 -1
  119. package/dist/custom/visualization/shared/svg-utils.js +54 -19
  120. package/dist/custom/visualization/shared/svg-utils.js.map +1 -1
  121. package/dist/custom/web/rss-feed-parsing.d.ts.map +1 -1
  122. package/dist/custom/web/rss-feed-parsing.js +15 -1
  123. package/dist/custom/web/rss-feed-parsing.js.map +1 -1
  124. package/dist/custom/web/url-metadata-extractor.action.d.ts.map +1 -1
  125. package/dist/custom/web/url-metadata-extractor.action.js +21 -8
  126. package/dist/custom/web/url-metadata-extractor.action.js.map +1 -1
  127. package/dist/index.d.ts +7 -0
  128. package/dist/index.d.ts.map +1 -1
  129. package/dist/index.js +8 -0
  130. package/dist/index.js.map +1 -1
  131. package/package.json +46 -45
@@ -0,0 +1,891 @@
1
+ /**
2
+ * @fileoverview Zero-dependency GitHub REST + Git Data API client with policy guardrails.
3
+ *
4
+ * Implements:
5
+ * - Exponential backoff retry on transient network errors (ECONNRESET/ETIMEDOUT/502/503/504)
6
+ * and GitHub rate limits (429 / secondary rate limit with Retry-After)
7
+ * - Repository allowlist enforcement (`IsRepositoryAllowed`)
8
+ * - Protected branch guardrails (`main`, `master`, `next`, `production`, and repo default branch)
9
+ * - App-token-never-merges policy (`auth.AllowMerge === true` required for `MergePullRequest`)
10
+ * - Atomic multi-file Git Data API commits (`CommitFiles` & `CommitFilesAndCreatePR`)
11
+ * - Compound context endpoints (`GetRepositoryContext`, `GetPullRequestContext`)
12
+ *
13
+ * @module @memberjunction/core-actions/github
14
+ */
15
+ import { IsRepositoryAllowed, TrimSlashes, TrimTrailingSlashes } from './github-app-auth.js';
16
+ /** Default branch names treated as protected unless `AllowProtectedBranch: true` is passed. */
17
+ export const DEFAULT_PROTECTED_BRANCHES = new Set([
18
+ 'main',
19
+ 'master',
20
+ 'next',
21
+ 'production',
22
+ ]);
23
+ /** Maximum file size (in bytes) sent inline in `git/trees` before falling back to `git/blobs`. */
24
+ const MAX_INLINE_TREE_FILE_BYTES = 1024 * 1024; // 1 MiB
25
+ // ============================================================================
26
+ // Typed Error Hierarchy
27
+ // ============================================================================
28
+ export class GitHubRequestError extends Error {
29
+ constructor(message, statusCode, endpoint, responseBody) {
30
+ super(message);
31
+ this.name = 'GitHubRequestError';
32
+ this.StatusCode = statusCode;
33
+ this.Endpoint = endpoint;
34
+ this.ResponseBody = responseBody;
35
+ }
36
+ }
37
+ export class GitHubAuthError extends GitHubRequestError {
38
+ constructor(message, statusCode, endpoint, responseBody) {
39
+ super(message, statusCode, endpoint, responseBody);
40
+ this.name = 'GitHubAuthError';
41
+ }
42
+ }
43
+ export class GitHubNotFoundError extends GitHubRequestError {
44
+ constructor(message, endpoint, responseBody) {
45
+ super(message, 404, endpoint, responseBody);
46
+ this.name = 'GitHubNotFoundError';
47
+ }
48
+ }
49
+ export class GitHubRateLimitError extends GitHubRequestError {
50
+ constructor(message, statusCode, endpoint, retryAfterSeconds, responseBody) {
51
+ super(message, statusCode, endpoint, responseBody);
52
+ this.name = 'GitHubRateLimitError';
53
+ this.RetryAfterSeconds = retryAfterSeconds;
54
+ }
55
+ }
56
+ export class GitHubPolicyError extends Error {
57
+ constructor(policyCode, message) {
58
+ super(message);
59
+ this.name = 'GitHubPolicyError';
60
+ this.PolicyCode = policyCode;
61
+ }
62
+ }
63
+ // ============================================================================
64
+ // GitHubRestClient Implementation
65
+ // ============================================================================
66
+ export class GitHubRestClient {
67
+ constructor(auth, options = {}) {
68
+ this.auth = auth;
69
+ this.fetchImpl = options.FetchImpl ?? fetch;
70
+ this.maxRetries = options.MaxRetries ?? 3;
71
+ this.baseRetryDelayMs = options.BaseRetryDelayMs ?? 250;
72
+ }
73
+ get Auth() {
74
+ return this.auth;
75
+ }
76
+ // ------------------------------------------------------------------------
77
+ // Policy Guardrails
78
+ // ------------------------------------------------------------------------
79
+ /**
80
+ * Enforces the credential's `AllowedRepositories` policy before making any repo-scoped call.
81
+ */
82
+ AssertRepositoryAllowed(owner, repo) {
83
+ if (!IsRepositoryAllowed(owner, repo, this.auth.AllowedRepositories)) {
84
+ throw new GitHubPolicyError('REPO_NOT_ALLOWED', `Repository '${owner}/${repo}' is not permitted by this credential's AllowedRepositories policy (${(this.auth.AllowedRepositories ?? []).join(', ')}).`);
85
+ }
86
+ }
87
+ /**
88
+ * Enforces the protected branch policy (`main`, `master`, `next`, `production`, or the repo's default branch).
89
+ */
90
+ AssertProtectedBranchAllowed(branch, defaultBranch, allowProtectedBranch) {
91
+ if (allowProtectedBranch === true) {
92
+ return;
93
+ }
94
+ const normalized = branch.replace(/^refs\/heads\//, '').trim();
95
+ const isDefault = defaultBranch ? normalized.toLowerCase() === defaultBranch.toLowerCase() : false;
96
+ const isStandardProtected = DEFAULT_PROTECTED_BRANCHES.has(normalized.toLowerCase());
97
+ if (isDefault || isStandardProtected) {
98
+ throw new GitHubPolicyError('PROTECTED_BRANCH', `Direct commits to protected branch '${normalized}' are blocked by policy. Create a feature branch and open a Pull Request, or explicitly pass AllowProtectedBranch=true if authorized.`);
99
+ }
100
+ }
101
+ /**
102
+ * Enforces the `app-token-never-merges` review separation boundary.
103
+ */
104
+ AssertMergeAllowed() {
105
+ if (!this.auth.AllowMerge) {
106
+ throw new GitHubPolicyError('MERGE_NOT_ALLOWED', `Merging Pull Requests is disabled for this credential (AuthKind=${this.auth.AuthKind}, AllowMerge=false). In accordance with the app-token-never-merges policy, agent tokens may open and review PRs, while merging requires a credential with allowMerge=true or a human-delegated token.`);
107
+ }
108
+ }
109
+ // ------------------------------------------------------------------------
110
+ // 1. Repository Context & File / Tree / Code Discovery
111
+ // ------------------------------------------------------------------------
112
+ /**
113
+ * Fetches a token-efficient compound overview of a repository in parallel:
114
+ * metadata, languages, top-level tree, README preview, and recent releases.
115
+ */
116
+ async GetRepositoryContext(owner, repo) {
117
+ this.AssertRepositoryAllowed(owner, repo);
118
+ const encOwner = encodeURIComponent(owner);
119
+ const encRepo = encodeURIComponent(repo);
120
+ const repoData = await this.RequestJson('GET', `/repos/${encOwner}/${encRepo}`);
121
+ const defaultBranch = String(repoData.default_branch ?? 'main');
122
+ const [languages, treeData, readmeText, releases] = await Promise.all([
123
+ this.RequestJson('GET', `/repos/${encOwner}/${encRepo}/languages`).catch(() => ({})),
124
+ this.RequestJson('GET', `/repos/${encOwner}/${encRepo}/git/trees/${encodeURIComponent(defaultBranch)}`).catch(() => ({ tree: [] })),
125
+ this.fetchReadmePreview(owner, repo, defaultBranch),
126
+ this.RequestJson('GET', `/repos/${encOwner}/${encRepo}/releases?per_page=5`).catch(() => []),
127
+ ]);
128
+ const topLevelEntries = (treeData.tree ?? [])
129
+ .filter((item) => item.type === 'blob' || item.type === 'tree')
130
+ .slice(0, 100)
131
+ .map((item) => ({
132
+ path: item.path,
133
+ type: item.type,
134
+ ...(item.size !== undefined ? { size: item.size } : {}),
135
+ }));
136
+ return {
137
+ Owner: owner,
138
+ Repo: repo,
139
+ FullName: String(repoData.full_name ?? `${owner}/${repo}`),
140
+ Description: typeof repoData.description === 'string' ? repoData.description : null,
141
+ DefaultBranch: defaultBranch,
142
+ Private: Boolean(repoData.private),
143
+ HtmlUrl: String(repoData.html_url ?? `https://github.com/${owner}/${repo}`),
144
+ Topics: Array.isArray(repoData.topics) ? repoData.topics : [],
145
+ Languages: languages,
146
+ TopLevelEntries: topLevelEntries,
147
+ ReadmePreview: readmeText,
148
+ RecentReleases: releases.slice(0, 5).map((rel) => ({
149
+ tagName: String(rel.tag_name ?? ''),
150
+ name: typeof rel.name === 'string' ? rel.name : null,
151
+ prerelease: Boolean(rel.prerelease),
152
+ publishedAt: typeof rel.published_at === 'string' ? rel.published_at : null,
153
+ })),
154
+ };
155
+ }
156
+ /**
157
+ * Reads one or more files from a repository at an optional ref and optional 1-indexed line slice.
158
+ */
159
+ async ReadFiles(owner, repo, paths, ref, startLine, endLine) {
160
+ this.AssertRepositoryAllowed(owner, repo);
161
+ const encOwner = encodeURIComponent(owner);
162
+ const encRepo = encodeURIComponent(repo);
163
+ let effectiveRef = ref?.trim();
164
+ if (!effectiveRef) {
165
+ const repoInfo = await this.RequestJson('GET', `/repos/${encOwner}/${encRepo}`);
166
+ effectiveRef = repoInfo.default_branch ?? 'main';
167
+ }
168
+ const results = [];
169
+ for (const rawPath of paths) {
170
+ const cleanPath = rawPath.replace(/^\/+/, '');
171
+ const encodedPath = cleanPath.split('/').map(encodeURIComponent).join('/');
172
+ const query = `?ref=${encodeURIComponent(effectiveRef)}`;
173
+ const fileData = await this.RequestJson('GET', `/repos/${encOwner}/${encRepo}/contents/${encodedPath}${query}`);
174
+ if (fileData.type && fileData.type !== 'file') {
175
+ throw new GitHubRequestError(`Path '${cleanPath}' is a '${fileData.type}', not a file. Use ListTree to inspect directories.`, 400, `/repos/${encOwner}/${encRepo}/contents/${encodedPath}`);
176
+ }
177
+ const fullText = fileData.encoding === 'base64' && typeof fileData.content === 'string'
178
+ ? Buffer.from(fileData.content.replace(/\s+/g, ''), 'base64').toString('utf8')
179
+ : String(fileData.content ?? '');
180
+ const lines = fullText.split(/\r?\n/);
181
+ const totalLines = lines.length;
182
+ const sLine = startLine && startLine >= 1 ? Math.min(startLine, totalLines) : 1;
183
+ const eLine = endLine && endLine >= sLine ? Math.min(endLine, totalLines) : totalLines;
184
+ const slicedContent = lines.slice(sLine - 1, eLine).join('\n');
185
+ results.push({
186
+ Path: fileData.path ?? cleanPath,
187
+ Ref: effectiveRef,
188
+ Sha: String(fileData.sha ?? ''),
189
+ Size: Number(fileData.size ?? Buffer.byteLength(fullText, 'utf8')),
190
+ TotalLines: totalLines,
191
+ StartLine: sLine,
192
+ EndLine: eLine,
193
+ Content: slicedContent,
194
+ HtmlUrl: fileData.html_url ?? null,
195
+ });
196
+ }
197
+ return results;
198
+ }
199
+ /**
200
+ * Lists a repository's file tree with optional path prefix, glob filter, and depth limit.
201
+ */
202
+ async ListTree(owner, repo, ref, pathPrefix, globPattern, maxDepth, limit = 500) {
203
+ this.AssertRepositoryAllowed(owner, repo);
204
+ const encOwner = encodeURIComponent(owner);
205
+ const encRepo = encodeURIComponent(repo);
206
+ let effectiveRef = ref?.trim();
207
+ if (!effectiveRef) {
208
+ const repoInfo = await this.RequestJson('GET', `/repos/${encOwner}/${encRepo}`);
209
+ effectiveRef = repoInfo.default_branch ?? 'main';
210
+ }
211
+ const treeResponse = await this.RequestJson('GET', `/repos/${encOwner}/${encRepo}/git/trees/${encodeURIComponent(effectiveRef)}?recursive=1`);
212
+ const cleanPrefix = pathPrefix ? TrimSlashes(pathPrefix) : '';
213
+ const globRegex = globPattern ? GlobToRegExp(globPattern) : null;
214
+ const matched = (treeResponse.tree ?? []).filter((entry) => {
215
+ if (cleanPrefix && entry.path !== cleanPrefix && !entry.path.startsWith(`${cleanPrefix}/`)) {
216
+ return false;
217
+ }
218
+ if (maxDepth !== undefined && maxDepth > 0) {
219
+ const relativePath = cleanPrefix ? entry.path.slice(cleanPrefix.length).replace(/^\/+/, '') : entry.path;
220
+ const depth = relativePath ? relativePath.split('/').length : 0;
221
+ if (depth > maxDepth) {
222
+ return false;
223
+ }
224
+ }
225
+ if (globRegex && !globRegex.test(entry.path)) {
226
+ return false;
227
+ }
228
+ return true;
229
+ });
230
+ return {
231
+ Ref: effectiveRef,
232
+ Truncated: Boolean(treeResponse.truncated) || matched.length > limit,
233
+ TotalMatched: matched.length,
234
+ Entries: matched.slice(0, limit),
235
+ };
236
+ }
237
+ /**
238
+ * Searches code across a repository or organization.
239
+ */
240
+ async SearchCode(query, owner, repo, perPage = 25) {
241
+ if (owner && repo) {
242
+ this.AssertRepositoryAllowed(owner, repo);
243
+ }
244
+ let qualifiedQuery = query.trim();
245
+ if (owner && repo && !/\brepo:/i.test(qualifiedQuery)) {
246
+ qualifiedQuery = `${qualifiedQuery} repo:${owner}/${repo}`;
247
+ }
248
+ else if (owner && !repo && !/\b(org|user):/i.test(qualifiedQuery)) {
249
+ qualifiedQuery = `${qualifiedQuery} org:${owner}`;
250
+ }
251
+ const clampedPerPage = Math.max(1, Math.min(100, perPage));
252
+ const response = await this.RequestJson('GET', `/search/code?q=${encodeURIComponent(qualifiedQuery)}&per_page=${clampedPerPage}`, undefined, 'application/vnd.github.text-match+json');
253
+ return {
254
+ TotalCount: Number(response.total_count ?? 0),
255
+ Items: (response.items ?? []).map((item) => ({
256
+ name: item.name,
257
+ path: item.path,
258
+ sha: item.sha,
259
+ htmlUrl: item.html_url,
260
+ repository: item.repository?.full_name ?? (owner && repo ? `${owner}/${repo}` : ''),
261
+ textMatches: (item.text_matches ?? [])
262
+ .map((m) => m.fragment ?? '')
263
+ .filter((f) => f.length > 0),
264
+ })),
265
+ };
266
+ }
267
+ // ------------------------------------------------------------------------
268
+ // 2. Atomic Multi-File Commits via Git Data API
269
+ // ------------------------------------------------------------------------
270
+ /**
271
+ * Commits one or more file additions, updates, or deletions in a single atomic commit
272
+ * using the GitHub Git Data API (`git/refs` -> `git/commits` -> `git/trees` -> `git/commits` -> `git/refs`).
273
+ */
274
+ async CommitFiles(params) {
275
+ this.AssertRepositoryAllowed(params.Owner, params.Repo);
276
+ if (!params.Files || params.Files.length === 0) {
277
+ throw new Error('CommitFiles requires at least one file in Files.');
278
+ }
279
+ const encOwner = encodeURIComponent(params.Owner);
280
+ const encRepo = encodeURIComponent(params.Repo);
281
+ const targetBranch = params.Branch.replace(/^refs\/heads\//, '').trim();
282
+ // Fetch repo metadata to know default_branch for protected branch check & BaseBranch fallback
283
+ const repoInfo = await this.RequestJson('GET', `/repos/${encOwner}/${encRepo}`);
284
+ const defaultBranch = repoInfo.default_branch ?? 'main';
285
+ const baseBranch = (params.BaseBranch ?? defaultBranch).replace(/^refs\/heads\//, '').trim();
286
+ // Enforce protected branch policy on the target branch
287
+ this.AssertProtectedBranchAllowed(targetBranch, defaultBranch, params.AllowProtectedBranch);
288
+ // 1. Resolve the parent commit SHA and ensure the target branch ref exists
289
+ let parentCommitSha;
290
+ let branchExists = false;
291
+ try {
292
+ const existingRef = await this.RequestJson('GET', `/repos/${encOwner}/${encRepo}/git/ref/heads/${encodeURIComponent(targetBranch)}`);
293
+ parentCommitSha = existingRef.object.sha;
294
+ branchExists = true;
295
+ }
296
+ catch (err) {
297
+ if (err instanceof GitHubNotFoundError && (params.CreateBranch ?? true)) {
298
+ const baseRef = await this.RequestJson('GET', `/repos/${encOwner}/${encRepo}/git/ref/heads/${encodeURIComponent(baseBranch)}`);
299
+ parentCommitSha = baseRef.object.sha;
300
+ await this.RequestJson('POST', `/repos/${encOwner}/${encRepo}/git/refs`, {
301
+ ref: `refs/heads/${targetBranch}`,
302
+ sha: parentCommitSha,
303
+ });
304
+ branchExists = true;
305
+ }
306
+ else {
307
+ throw err;
308
+ }
309
+ }
310
+ // 2. Fetch the base tree SHA from the parent commit
311
+ const parentCommit = await this.RequestJson('GET', `/repos/${encOwner}/${encRepo}/git/commits/${parentCommitSha}`);
312
+ const baseTreeSha = parentCommit.tree.sha;
313
+ // 3. Build tree entries (inline for UTF-8 files <= 1 MiB, blobs for > 1 MiB or base64, sha: null for delete)
314
+ let inlineFileCount = 0;
315
+ let blobFileCount = 0;
316
+ const treeEntries = [];
317
+ for (const file of params.Files) {
318
+ const cleanPath = file.path.replace(/^\/+/, '');
319
+ if (file.delete) {
320
+ treeEntries.push({
321
+ path: cleanPath,
322
+ mode: '100644',
323
+ type: 'blob',
324
+ sha: null,
325
+ });
326
+ continue;
327
+ }
328
+ const rawContent = file.content ?? '';
329
+ const encoding = file.encoding ?? 'utf-8';
330
+ const byteLength = encoding === 'base64'
331
+ ? Buffer.byteLength(rawContent, 'base64')
332
+ : Buffer.byteLength(rawContent, 'utf8');
333
+ if (encoding === 'utf-8' && byteLength <= MAX_INLINE_TREE_FILE_BYTES) {
334
+ treeEntries.push({
335
+ path: cleanPath,
336
+ mode: '100644',
337
+ type: 'blob',
338
+ content: rawContent,
339
+ });
340
+ inlineFileCount++;
341
+ }
342
+ else {
343
+ const blob = await this.RequestJson('POST', `/repos/${encOwner}/${encRepo}/git/blobs`, {
344
+ content: rawContent,
345
+ encoding,
346
+ });
347
+ treeEntries.push({
348
+ path: cleanPath,
349
+ mode: '100644',
350
+ type: 'blob',
351
+ sha: blob.sha,
352
+ });
353
+ blobFileCount++;
354
+ }
355
+ }
356
+ // 4. Create the new Git tree
357
+ const newTree = await this.RequestJson('POST', `/repos/${encOwner}/${encRepo}/git/trees`, {
358
+ base_tree: baseTreeSha,
359
+ tree: treeEntries,
360
+ });
361
+ // 5. Create the commit object
362
+ const commitBody = {
363
+ message: params.Message,
364
+ tree: newTree.sha,
365
+ parents: [parentCommitSha],
366
+ };
367
+ if (params.Author) {
368
+ commitBody.author = params.Author;
369
+ }
370
+ const newCommit = await this.RequestJson('POST', `/repos/${encOwner}/${encRepo}/git/commits`, commitBody);
371
+ // 6. Advance the branch ref to the new commit SHA
372
+ if (branchExists) {
373
+ await this.RequestJson('PATCH', `/repos/${encOwner}/${encRepo}/git/refs/heads/${encodeURIComponent(targetBranch)}`, {
374
+ sha: newCommit.sha,
375
+ force: false,
376
+ });
377
+ }
378
+ return {
379
+ Branch: targetBranch,
380
+ BaseBranch: baseBranch,
381
+ CommitSha: newCommit.sha,
382
+ TreeSha: newTree.sha,
383
+ CommitUrl: newCommit.html_url ?? `https://github.com/${params.Owner}/${params.Repo}/commit/${newCommit.sha}`,
384
+ FilesCommitted: params.Files.length,
385
+ InlineFileCount: inlineFileCount,
386
+ BlobFileCount: blobFileCount,
387
+ };
388
+ }
389
+ /**
390
+ * Compound workflow: creates/updates a feature branch with an atomic multi-file commit
391
+ * and opens (or reuses an existing open) Pull Request in a single operation.
392
+ */
393
+ async CommitFilesAndCreatePR(params) {
394
+ const commitResult = await this.CommitFiles({
395
+ ...params.Commit,
396
+ CreateBranch: params.Commit.CreateBranch ?? true,
397
+ });
398
+ // Check if an open PR already exists for this head -> base branch
399
+ const existingPRs = await this.RequestJson('GET', `/repos/${encodeURIComponent(params.Commit.Owner)}/${encodeURIComponent(params.Commit.Repo)}/pulls?state=open&head=${encodeURIComponent(`${params.Commit.Owner}:${commitResult.Branch}`)}&base=${encodeURIComponent(commitResult.BaseBranch)}`);
400
+ if (existingPRs.length > 0) {
401
+ const pr = MapPullRequestSummary(existingPRs[0]);
402
+ return {
403
+ CommitResult: commitResult,
404
+ PullRequest: pr,
405
+ CreatedNewPR: false,
406
+ };
407
+ }
408
+ const pr = await this.CreatePullRequest({
409
+ Owner: params.Commit.Owner,
410
+ Repo: params.Commit.Repo,
411
+ Title: params.PRTitle,
412
+ Body: params.PRBody,
413
+ Head: commitResult.Branch,
414
+ Base: commitResult.BaseBranch,
415
+ Draft: params.Draft,
416
+ Labels: params.Labels,
417
+ Assignees: params.Assignees,
418
+ Reviewers: params.Reviewers,
419
+ });
420
+ return {
421
+ CommitResult: commitResult,
422
+ PullRequest: pr,
423
+ CreatedNewPR: true,
424
+ };
425
+ }
426
+ // ------------------------------------------------------------------------
427
+ // 3. Pull Requests, Reviews & Merging
428
+ // ------------------------------------------------------------------------
429
+ /**
430
+ * Creates a new Pull Request and optionally applies labels, assignees, and reviewers.
431
+ * Defaults `Draft` to `this.auth.DefaultPRMode === 'draft'` when omitted.
432
+ */
433
+ async CreatePullRequest(params) {
434
+ this.AssertRepositoryAllowed(params.Owner, params.Repo);
435
+ const encOwner = encodeURIComponent(params.Owner);
436
+ const encRepo = encodeURIComponent(params.Repo);
437
+ let baseBranch = params.Base?.trim();
438
+ if (!baseBranch) {
439
+ const repoInfo = await this.RequestJson('GET', `/repos/${encOwner}/${encRepo}`);
440
+ baseBranch = repoInfo.default_branch ?? 'main';
441
+ }
442
+ const isDraft = params.Draft ?? (this.auth.DefaultPRMode === 'draft');
443
+ const created = await this.RequestJson('POST', `/repos/${encOwner}/${encRepo}/pulls`, {
444
+ title: params.Title,
445
+ body: params.Body ?? '',
446
+ head: params.Head.replace(/^refs\/heads\//, ''),
447
+ base: baseBranch.replace(/^refs\/heads\//, ''),
448
+ draft: isDraft,
449
+ });
450
+ const prNumber = Number(created.number);
451
+ // Apply labels & assignees if requested
452
+ if (params.Labels && params.Labels.length > 0) {
453
+ await this.RequestJson('POST', `/repos/${encOwner}/${encRepo}/issues/${prNumber}/labels`, {
454
+ labels: params.Labels,
455
+ }).catch(() => undefined);
456
+ }
457
+ if (params.Assignees && params.Assignees.length > 0) {
458
+ await this.RequestJson('POST', `/repos/${encOwner}/${encRepo}/issues/${prNumber}/assignees`, {
459
+ assignees: params.Assignees,
460
+ }).catch(() => undefined);
461
+ }
462
+ if (params.Reviewers && params.Reviewers.length > 0) {
463
+ await this.RequestJson('POST', `/repos/${encOwner}/${encRepo}/pulls/${prNumber}/requested_reviewers`, {
464
+ reviewers: params.Reviewers,
465
+ }).catch(() => undefined);
466
+ }
467
+ return MapPullRequestSummary(created);
468
+ }
469
+ /**
470
+ * Fetches a complete, compound Pull Request context in parallel:
471
+ * PR metadata, changed files (with optional patches), reviews, inline review comments, and check runs.
472
+ */
473
+ async GetPullRequestContext(owner, repo, pullNumber, includePatches = true) {
474
+ this.AssertRepositoryAllowed(owner, repo);
475
+ const encOwner = encodeURIComponent(owner);
476
+ const encRepo = encodeURIComponent(repo);
477
+ const prData = await this.RequestJson('GET', `/repos/${encOwner}/${encRepo}/pulls/${pullNumber}`);
478
+ const summary = MapPullRequestSummary(prData);
479
+ const [filesData, reviewsData, commentsData, checksData] = await Promise.all([
480
+ this.RequestJson('GET', `/repos/${encOwner}/${encRepo}/pulls/${pullNumber}/files?per_page=100`).catch(() => []),
481
+ this.RequestJson('GET', `/repos/${encOwner}/${encRepo}/pulls/${pullNumber}/reviews?per_page=100`).catch(() => []),
482
+ this.RequestJson('GET', `/repos/${encOwner}/${encRepo}/pulls/${pullNumber}/comments?per_page=100`).catch(() => []),
483
+ summary.HeadSha
484
+ ? this.RequestJson('GET', `/repos/${encOwner}/${encRepo}/commits/${encodeURIComponent(summary.HeadSha)}/check-runs?per_page=100`).catch(() => ({ check_runs: [] }))
485
+ : Promise.resolve({ check_runs: [] }),
486
+ ]);
487
+ return {
488
+ PullRequest: {
489
+ ...summary,
490
+ Body: typeof prData.body === 'string' ? prData.body : null,
491
+ Additions: Number(prData.additions ?? 0),
492
+ Deletions: Number(prData.deletions ?? 0),
493
+ ChangedFilesCount: Number(prData.changed_files ?? filesData.length),
494
+ },
495
+ Files: filesData.map((f) => ({
496
+ filename: String(f.filename ?? ''),
497
+ status: String(f.status ?? 'modified'),
498
+ additions: Number(f.additions ?? 0),
499
+ deletions: Number(f.deletions ?? 0),
500
+ ...(includePatches && typeof f.patch === 'string' ? { patch: f.patch } : {}),
501
+ })),
502
+ Reviews: reviewsData.map((r) => ({
503
+ id: Number(r.id ?? 0),
504
+ user: String(r.user?.login ?? ''),
505
+ state: String(r.state ?? ''),
506
+ body: typeof r.body === 'string' ? r.body : null,
507
+ submittedAt: typeof r.submitted_at === 'string' ? r.submitted_at : null,
508
+ })),
509
+ ReviewComments: commentsData.map((c) => ({
510
+ id: Number(c.id ?? 0),
511
+ user: String(c.user?.login ?? ''),
512
+ path: String(c.path ?? ''),
513
+ line: typeof c.line === 'number' ? c.line : null,
514
+ body: String(c.body ?? ''),
515
+ createdAt: String(c.created_at ?? ''),
516
+ })),
517
+ CheckRuns: (checksData.check_runs ?? []).map((cr) => ({
518
+ id: Number(cr.id ?? 0),
519
+ name: String(cr.name ?? ''),
520
+ status: String(cr.status ?? ''),
521
+ conclusion: typeof cr.conclusion === 'string' ? cr.conclusion : null,
522
+ htmlUrl: typeof cr.html_url === 'string' ? cr.html_url : null,
523
+ })),
524
+ };
525
+ }
526
+ /**
527
+ * Submits a Pull Request review (`APPROVE`, `REQUEST_CHANGES`, or `COMMENT`) with optional line comments.
528
+ */
529
+ async SubmitPullRequestReview(params) {
530
+ this.AssertRepositoryAllowed(params.Owner, params.Repo);
531
+ const encOwner = encodeURIComponent(params.Owner);
532
+ const encRepo = encodeURIComponent(params.Repo);
533
+ const payload = {
534
+ event: params.Event,
535
+ body: params.Body ?? '',
536
+ };
537
+ if (params.Comments && params.Comments.length > 0) {
538
+ payload.comments = params.Comments.map((c) => ({
539
+ path: c.path.replace(/^\/+/, ''),
540
+ line: c.line,
541
+ side: c.side ?? 'RIGHT',
542
+ body: c.body,
543
+ }));
544
+ }
545
+ const result = await this.RequestJson('POST', `/repos/${encOwner}/${encRepo}/pulls/${params.PullNumber}/reviews`, payload);
546
+ return {
547
+ ReviewId: Number(result.id ?? 0),
548
+ State: String(result.state ?? params.Event),
549
+ HtmlUrl: String(result.html_url ?? ''),
550
+ };
551
+ }
552
+ /**
553
+ * Merges a Pull Request.
554
+ * Enforces `AssertMergeAllowed()` (`auth.AllowMerge === true`) to uphold the `app-token-never-merges` boundary.
555
+ */
556
+ async MergePullRequest(params) {
557
+ this.AssertRepositoryAllowed(params.Owner, params.Repo);
558
+ this.AssertMergeAllowed();
559
+ const encOwner = encodeURIComponent(params.Owner);
560
+ const encRepo = encodeURIComponent(params.Repo);
561
+ const body = {
562
+ merge_method: params.MergeMethod ?? 'squash',
563
+ };
564
+ if (params.CommitTitle)
565
+ body.commit_title = params.CommitTitle;
566
+ if (params.CommitMessage)
567
+ body.commit_message = params.CommitMessage;
568
+ if (params.Sha)
569
+ body.sha = params.Sha;
570
+ const result = await this.RequestJson('PUT', `/repos/${encOwner}/${encRepo}/pulls/${params.PullNumber}/merge`, body);
571
+ return {
572
+ Merged: Boolean(result.merged),
573
+ Sha: String(result.sha ?? ''),
574
+ Message: String(result.message ?? ''),
575
+ };
576
+ }
577
+ // ------------------------------------------------------------------------
578
+ // 4. Issues, PR Search & Comments
579
+ // ------------------------------------------------------------------------
580
+ /**
581
+ * Searches GitHub Issues and Pull Requests using GitHub search qualifiers.
582
+ */
583
+ async SearchIssuesAndPRs(params) {
584
+ if (params.Owner && params.Repo) {
585
+ this.AssertRepositoryAllowed(params.Owner, params.Repo);
586
+ }
587
+ let q = params.Query.trim();
588
+ if (params.Owner && params.Repo && !/\brepo:/i.test(q)) {
589
+ q = `${q} repo:${params.Owner}/${params.Repo}`;
590
+ }
591
+ else if (params.Owner && !params.Repo && !/\b(org|user):/i.test(q)) {
592
+ q = `${q} org:${params.Owner}`;
593
+ }
594
+ const perPage = Math.max(1, Math.min(100, params.PerPage ?? 25));
595
+ const res = await this.RequestJson('GET', `/search/issues?q=${encodeURIComponent(q)}&per_page=${perPage}`);
596
+ return {
597
+ TotalCount: Number(res.total_count ?? 0),
598
+ Items: (res.items ?? []).map((item) => ({
599
+ number: Number(item.number ?? 0),
600
+ title: String(item.title ?? ''),
601
+ state: String(item.state ?? ''),
602
+ isPullRequest: Boolean(item.pull_request),
603
+ htmlUrl: String(item.html_url ?? ''),
604
+ author: String(item.user?.login ?? ''),
605
+ labels: Array.isArray(item.labels)
606
+ ? item.labels.map((l) => (typeof l === 'string' ? l : String(l.name ?? '')))
607
+ : [],
608
+ createdAt: String(item.created_at ?? ''),
609
+ updatedAt: String(item.updated_at ?? ''),
610
+ })),
611
+ };
612
+ }
613
+ /**
614
+ * Creates a new Issue (when `IssueNumber` is omitted) or updates an existing Issue.
615
+ */
616
+ async CreateOrUpdateIssue(params) {
617
+ this.AssertRepositoryAllowed(params.Owner, params.Repo);
618
+ const encOwner = encodeURIComponent(params.Owner);
619
+ const encRepo = encodeURIComponent(params.Repo);
620
+ const payload = {};
621
+ if (params.Title !== undefined)
622
+ payload.title = params.Title;
623
+ if (params.Body !== undefined)
624
+ payload.body = params.Body;
625
+ if (params.State !== undefined)
626
+ payload.state = params.State;
627
+ if (params.Labels !== undefined)
628
+ payload.labels = params.Labels;
629
+ if (params.Assignees !== undefined)
630
+ payload.assignees = params.Assignees;
631
+ const endpoint = params.IssueNumber
632
+ ? `/repos/${encOwner}/${encRepo}/issues/${params.IssueNumber}`
633
+ : `/repos/${encOwner}/${encRepo}/issues`;
634
+ const method = params.IssueNumber ? 'PATCH' : 'POST';
635
+ const result = await this.RequestJson(method, endpoint, payload);
636
+ return {
637
+ Number: Number(result.number ?? 0),
638
+ Title: String(result.title ?? ''),
639
+ State: String(result.state ?? 'open'),
640
+ HtmlUrl: String(result.html_url ?? ''),
641
+ };
642
+ }
643
+ /**
644
+ * Adds a comment to an Issue or Pull Request.
645
+ */
646
+ async AddComment(params) {
647
+ this.AssertRepositoryAllowed(params.Owner, params.Repo);
648
+ const encOwner = encodeURIComponent(params.Owner);
649
+ const encRepo = encodeURIComponent(params.Repo);
650
+ const result = await this.RequestJson('POST', `/repos/${encOwner}/${encRepo}/issues/${params.IssueNumber}/comments`, { body: params.Body });
651
+ return {
652
+ CommentId: Number(result.id ?? 0),
653
+ HtmlUrl: String(result.html_url ?? ''),
654
+ CreatedAt: String(result.created_at ?? ''),
655
+ };
656
+ }
657
+ // ------------------------------------------------------------------------
658
+ // 5. GitHub Actions Workflow Runs & Failed Job Diagnostics
659
+ // ------------------------------------------------------------------------
660
+ /**
661
+ * Inspects a workflow run (including failed jobs/steps and log tails),
662
+ * re-runs failed jobs, or dispatches a workflow.
663
+ */
664
+ async GetWorkflowRunAndLogs(params) {
665
+ this.AssertRepositoryAllowed(params.Owner, params.Repo);
666
+ const encOwner = encodeURIComponent(params.Owner);
667
+ const encRepo = encodeURIComponent(params.Repo);
668
+ const mode = params.Action ?? 'inspect';
669
+ if (mode === 'dispatch') {
670
+ if (!params.WorkflowIdOrFileName) {
671
+ throw new Error(`WorkflowIdOrFileName is required when Action='dispatch'.`);
672
+ }
673
+ const ref = params.Branch ?? 'main';
674
+ await this.RequestJson('POST', `/repos/${encOwner}/${encRepo}/actions/workflows/${encodeURIComponent(params.WorkflowIdOrFileName)}/dispatches`, {
675
+ ref,
676
+ inputs: params.DispatchInputs ?? {},
677
+ });
678
+ return {
679
+ Action: 'dispatch',
680
+ Dispatched: true,
681
+ };
682
+ }
683
+ // Resolve RunId if not explicitly given (pick latest run on Branch)
684
+ let runId = params.RunId;
685
+ if (!runId) {
686
+ const branchQuery = params.Branch ? `?branch=${encodeURIComponent(params.Branch)}&per_page=1` : '?per_page=1';
687
+ const runsRes = await this.RequestJson('GET', `/repos/${encOwner}/${encRepo}/actions/runs${branchQuery}`);
688
+ const latest = runsRes.workflow_runs?.[0];
689
+ if (!latest) {
690
+ throw new GitHubNotFoundError(`No workflow runs found for ${params.Owner}/${params.Repo}${params.Branch ? ` on branch '${params.Branch}'` : ''}.`, `/repos/${encOwner}/${encRepo}/actions/runs`);
691
+ }
692
+ runId = Number(latest.id);
693
+ }
694
+ if (mode === 'rerun-failed') {
695
+ await this.RequestJson('POST', `/repos/${encOwner}/${encRepo}/actions/runs/${runId}/rerun-failed-jobs`);
696
+ }
697
+ const runData = await this.RequestJson('GET', `/repos/${encOwner}/${encRepo}/actions/runs/${runId}`);
698
+ const jobsRes = await this.RequestJson('GET', `/repos/${encOwner}/${encRepo}/actions/runs/${runId}/jobs?per_page=50`);
699
+ const maxLogChars = params.MaxLogCharsPerJob ?? 4000;
700
+ const includeLogs = params.IncludeFailedJobLogs ?? true;
701
+ const jobs = [];
702
+ for (const j of jobsRes.jobs ?? []) {
703
+ const jobId = Number(j.id ?? 0);
704
+ const conclusion = typeof j.conclusion === 'string' ? j.conclusion : null;
705
+ const steps = Array.isArray(j.steps) ? j.steps : [];
706
+ const failedSteps = steps
707
+ .filter((s) => s.conclusion === 'failure' || s.conclusion === 'timed_out')
708
+ .map((s) => ({
709
+ name: String(s.name ?? ''),
710
+ number: Number(s.number ?? 0),
711
+ conclusion: typeof s.conclusion === 'string' ? s.conclusion : null,
712
+ }));
713
+ let logTail;
714
+ if (includeLogs && (conclusion === 'failure' || failedSteps.length > 0)) {
715
+ logTail = await this.fetchJobLogTail(params.Owner, params.Repo, jobId, maxLogChars);
716
+ }
717
+ jobs.push({
718
+ id: jobId,
719
+ name: String(j.name ?? ''),
720
+ status: String(j.status ?? ''),
721
+ conclusion,
722
+ startedAt: typeof j.started_at === 'string' ? j.started_at : null,
723
+ completedAt: typeof j.completed_at === 'string' ? j.completed_at : null,
724
+ failedSteps,
725
+ ...(logTail ? { logTail } : {}),
726
+ });
727
+ }
728
+ return {
729
+ Action: mode,
730
+ ...(mode === 'rerun-failed' ? { RerunTriggered: true } : {}),
731
+ Run: {
732
+ id: Number(runData.id ?? runId),
733
+ name: typeof runData.name === 'string' ? runData.name : null,
734
+ workflowId: Number(runData.workflow_id ?? 0),
735
+ headBranch: typeof runData.head_branch === 'string' ? runData.head_branch : null,
736
+ headSha: String(runData.head_sha ?? ''),
737
+ status: typeof runData.status === 'string' ? runData.status : null,
738
+ conclusion: typeof runData.conclusion === 'string' ? runData.conclusion : null,
739
+ htmlUrl: String(runData.html_url ?? ''),
740
+ createdAt: String(runData.created_at ?? ''),
741
+ updatedAt: String(runData.updated_at ?? ''),
742
+ },
743
+ Jobs: jobs,
744
+ };
745
+ }
746
+ // ------------------------------------------------------------------------
747
+ // Internal HTTP Transport & Retry Helpers
748
+ // ------------------------------------------------------------------------
749
+ async fetchReadmePreview(owner, repo, ref) {
750
+ try {
751
+ const data = await this.RequestJson('GET', `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/readme?ref=${encodeURIComponent(ref)}`);
752
+ if (data.encoding === 'base64' && typeof data.content === 'string') {
753
+ const decoded = Buffer.from(data.content.replace(/\s+/g, ''), 'base64').toString('utf8');
754
+ return decoded.length > 2000 ? `${decoded.slice(0, 2000)}\n...(truncated)` : decoded;
755
+ }
756
+ return null;
757
+ }
758
+ catch {
759
+ return null;
760
+ }
761
+ }
762
+ async fetchJobLogTail(owner, repo, jobId, maxChars) {
763
+ try {
764
+ const endpoint = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/actions/jobs/${jobId}/logs`;
765
+ const response = await this.requestRaw('GET', endpoint);
766
+ const text = await response.text();
767
+ if (!text)
768
+ return undefined;
769
+ return text.length > maxChars ? text.slice(-maxChars) : text;
770
+ }
771
+ catch {
772
+ return undefined;
773
+ }
774
+ }
775
+ async RequestJson(method, endpoint, body, acceptHeader = 'application/vnd.github+json') {
776
+ const response = await this.requestRaw(method, endpoint, body, acceptHeader);
777
+ if (response.status === 204) {
778
+ return {};
779
+ }
780
+ const text = await response.text();
781
+ if (!text) {
782
+ return {};
783
+ }
784
+ return JSON.parse(text);
785
+ }
786
+ async requestRaw(method, endpoint, body, acceptHeader = 'application/vnd.github+json') {
787
+ const url = endpoint.startsWith('http')
788
+ ? endpoint
789
+ : `${TrimTrailingSlashes(this.auth.ApiBaseUrl)}/${endpoint.replace(/^\/+/, '')}`;
790
+ let lastError;
791
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
792
+ try {
793
+ const headers = {
794
+ Accept: acceptHeader,
795
+ Authorization: `Bearer ${this.auth.Token}`,
796
+ 'X-GitHub-Api-Version': '2022-11-28',
797
+ 'User-Agent': 'MemberJunction-GitHub-Integration/1.0',
798
+ };
799
+ if (body !== undefined) {
800
+ headers['Content-Type'] = 'application/json';
801
+ }
802
+ const response = await this.fetchImpl(url, {
803
+ method,
804
+ headers,
805
+ body: body !== undefined ? JSON.stringify(body) : undefined,
806
+ });
807
+ if (response.ok) {
808
+ return response;
809
+ }
810
+ const responseText = await response.text();
811
+ // Check for transient 5xx or rate limit 429 / 403 secondary rate limit
812
+ const isRateLimited = response.status === 429 ||
813
+ (response.status === 403 &&
814
+ (response.headers.get('x-ratelimit-remaining') === '0' ||
815
+ /rate limit/i.test(responseText)));
816
+ const isTransientServer = response.status === 502 || response.status === 503 || response.status === 504;
817
+ if ((isRateLimited || isTransientServer) && attempt < this.maxRetries) {
818
+ const retryAfterHeader = response.headers.get('retry-after');
819
+ const retryAfterMs = retryAfterHeader
820
+ ? Number(retryAfterHeader) * 1000
821
+ : this.baseRetryDelayMs * Math.pow(2, attempt);
822
+ await Delay(Math.min(retryAfterMs, 5000));
823
+ continue;
824
+ }
825
+ if (isRateLimited) {
826
+ const retryAfterSec = response.headers.get('retry-after')
827
+ ? Number(response.headers.get('retry-after'))
828
+ : undefined;
829
+ throw new GitHubRateLimitError(`GitHub API rate limit exceeded (${response.status}) on ${method} ${endpoint}: ${responseText}`, response.status, endpoint, retryAfterSec, responseText);
830
+ }
831
+ if (response.status === 401 || response.status === 403) {
832
+ throw new GitHubAuthError(`GitHub authentication/authorization error (${response.status}) on ${method} ${endpoint}: ${responseText}`, response.status, endpoint, responseText);
833
+ }
834
+ if (response.status === 404) {
835
+ throw new GitHubNotFoundError(`GitHub resource not found (404) on ${method} ${endpoint}: ${responseText}`, endpoint, responseText);
836
+ }
837
+ throw new GitHubRequestError(`GitHub API error (${response.status}) on ${method} ${endpoint}: ${responseText}`, response.status, endpoint, responseText);
838
+ }
839
+ catch (err) {
840
+ lastError = err;
841
+ if (err instanceof GitHubRequestError) {
842
+ throw err;
843
+ }
844
+ const message = err instanceof Error ? err.message : String(err);
845
+ const isTransientNetwork = /ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|socket hang up|fetch failed/i.test(message);
846
+ if (isTransientNetwork && attempt < this.maxRetries) {
847
+ await Delay(this.baseRetryDelayMs * Math.pow(2, attempt));
848
+ continue;
849
+ }
850
+ throw err;
851
+ }
852
+ }
853
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
854
+ }
855
+ }
856
+ // ============================================================================
857
+ // Pure Mapping & Glob Helpers
858
+ // ============================================================================
859
+ function MapPullRequestSummary(raw) {
860
+ const head = (raw.head ?? {});
861
+ const base = (raw.base ?? {});
862
+ const user = (raw.user ?? {});
863
+ return {
864
+ Number: Number(raw.number ?? 0),
865
+ Title: String(raw.title ?? ''),
866
+ State: String(raw.state ?? 'open'),
867
+ Draft: Boolean(raw.draft),
868
+ HtmlUrl: String(raw.html_url ?? ''),
869
+ HeadBranch: String(head.ref ?? ''),
870
+ HeadSha: String(head.sha ?? ''),
871
+ BaseBranch: String(base.ref ?? ''),
872
+ Author: user.login,
873
+ Mergeable: typeof raw.mergeable === 'boolean' ? raw.mergeable : null,
874
+ CreatedAt: String(raw.created_at ?? ''),
875
+ UpdatedAt: String(raw.updated_at ?? ''),
876
+ };
877
+ }
878
+ function GlobToRegExp(glob) {
879
+ const escaped = glob
880
+ .trim()
881
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
882
+ .replace(/\*\*/g, '___DOUBLE_STAR___')
883
+ .replace(/\*/g, '[^/]*')
884
+ .replace(/\?/g, '[^/]')
885
+ .replace(/___DOUBLE_STAR___/g, '.*');
886
+ return new RegExp(`^${escaped}$`, 'i');
887
+ }
888
+ function Delay(ms) {
889
+ return new Promise((resolve) => setTimeout(resolve, ms));
890
+ }
891
+ //# sourceMappingURL=github-client.js.map