@aviaratech/ai-delivery 0.3.35 → 0.3.36

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 (297) hide show
  1. package/CONTRIBUTING.md +12 -206
  2. package/README.md +57 -554
  3. package/dist/agent.d.ts +0 -2
  4. package/dist/agent.js +76 -16
  5. package/dist/agent.js.map +7 -1
  6. package/dist/agentReadiness.test.js +73 -67
  7. package/dist/agentReadiness.test.js.map +7 -1
  8. package/dist/boardReconcile.test.js +1651 -1590
  9. package/dist/boardReconcile.test.js.map +7 -1
  10. package/dist/build.test.js +130 -0
  11. package/dist/build.test.js.map +7 -0
  12. package/dist/callerErrors.test.js +105 -0
  13. package/dist/callerErrors.test.js.map +7 -0
  14. package/dist/cli.js +402 -515
  15. package/dist/cli.js.map +7 -1
  16. package/dist/cliResult.d.ts +2 -2
  17. package/dist/cliResult.js +42 -45
  18. package/dist/cliResult.js.map +7 -1
  19. package/dist/cliResult.test.js +424 -369
  20. package/dist/cliResult.test.js.map +7 -1
  21. package/dist/config/deliveryConfig.d.ts +288 -14
  22. package/dist/config/deliveryConfig.js +472 -390
  23. package/dist/config/deliveryConfig.js.map +7 -1
  24. package/dist/config/deliveryConfig.test.js +773 -649
  25. package/dist/config/deliveryConfig.test.js.map +7 -1
  26. package/dist/contributorChecks.test.js +1694 -916
  27. package/dist/contributorChecks.test.js.map +7 -1
  28. package/dist/currentConsumer.test.js +819 -737
  29. package/dist/currentConsumer.test.js.map +7 -1
  30. package/dist/currentTrackingScenario.test.js +499 -479
  31. package/dist/currentTrackingScenario.test.js.map +7 -1
  32. package/dist/delivery/common.js +160 -172
  33. package/dist/delivery/common.js.map +7 -1
  34. package/dist/delivery/delivery.test.js +509 -431
  35. package/dist/delivery/delivery.test.js.map +7 -1
  36. package/dist/delivery/evidence.d.ts +2 -2
  37. package/dist/delivery/evidence.js +133 -120
  38. package/dist/delivery/evidence.js.map +7 -1
  39. package/dist/delivery/index.js +7 -2
  40. package/dist/delivery/index.js.map +7 -1
  41. package/dist/delivery/legacy.js +65 -5
  42. package/dist/delivery/legacy.js.map +7 -1
  43. package/dist/delivery/policy.d.ts +10 -10
  44. package/dist/delivery/policy.js +211 -238
  45. package/dist/delivery/policy.js.map +7 -1
  46. package/dist/delivery/stage.d.ts +18 -18
  47. package/dist/delivery/stage.js +220 -235
  48. package/dist/delivery/stage.js.map +7 -1
  49. package/dist/deliveryBoard.d.ts +74 -0
  50. package/dist/deliveryBoard.js +644 -0
  51. package/dist/deliveryBoard.js.map +7 -0
  52. package/dist/deliveryBoard.test.js +649 -0
  53. package/dist/deliveryBoard.test.js.map +7 -0
  54. package/dist/deliveryHealth.test.js +179 -155
  55. package/dist/deliveryHealth.test.js.map +7 -1
  56. package/dist/dependencyCompatibility.test.js +154 -140
  57. package/dist/dependencyCompatibility.test.js.map +7 -1
  58. package/dist/directoryIndependent.test.js +417 -383
  59. package/dist/directoryIndependent.test.js.map +7 -1
  60. package/dist/dispatch.d.ts +16 -11
  61. package/dist/dispatch.js +329 -353
  62. package/dist/dispatch.js.map +7 -1
  63. package/dist/errors.d.ts +3 -3
  64. package/dist/errors.js +103 -96
  65. package/dist/errors.js.map +7 -1
  66. package/dist/fixtures/deliveryBoardReplay.d.ts +56 -0
  67. package/dist/fixtures/deliveryBoardReplay.js +617 -0
  68. package/dist/fixtures/deliveryBoardReplay.js.map +7 -0
  69. package/dist/fixtures/discovery.d.ts +59 -19
  70. package/dist/fixtures/discovery.js +96 -90
  71. package/dist/fixtures/discovery.js.map +7 -1
  72. package/dist/fixtures/inertEntrypointChild.js +57 -56
  73. package/dist/fixtures/inertEntrypointChild.js.map +7 -1
  74. package/dist/fixtures/inertEntrypoints.d.ts +1 -1
  75. package/dist/fixtures/inertEntrypoints.js +321 -276
  76. package/dist/fixtures/inertEntrypoints.js.map +7 -1
  77. package/dist/fixtures/inertTarget.d.ts +78 -7
  78. package/dist/fixtures/inertTarget.js +769 -691
  79. package/dist/fixtures/inertTarget.js.map +7 -1
  80. package/dist/fixtures/issue63.d.ts +4 -3
  81. package/dist/fixtures/issue63.js +260 -274
  82. package/dist/fixtures/issue63.js.map +7 -1
  83. package/dist/fixtures/issueProjectItems.d.ts +20 -0
  84. package/dist/fixtures/issueProjectItems.js +15 -0
  85. package/dist/fixtures/issueProjectItems.js.map +7 -0
  86. package/dist/fixtures/readView.d.ts +120 -0
  87. package/dist/fixtures/readView.js +172 -0
  88. package/dist/fixtures/readView.js.map +7 -0
  89. package/dist/fixtures/recordedGitHubFlows.d.ts +120 -0
  90. package/dist/fixtures/recordedGitHubFlows.js +109 -0
  91. package/dist/fixtures/recordedGitHubFlows.js.map +7 -0
  92. package/dist/genericCompatibility.test.js +64 -55
  93. package/dist/genericCompatibility.test.js.map +7 -1
  94. package/dist/git.js +73 -67
  95. package/dist/git.js.map +7 -1
  96. package/dist/gitProcess.d.ts +1 -1
  97. package/dist/gitProcess.js +58 -53
  98. package/dist/gitProcess.js.map +7 -1
  99. package/dist/github/client.d.ts +2 -2
  100. package/dist/github/client.js +484 -379
  101. package/dist/github/client.js.map +7 -1
  102. package/dist/github/commandIdentityPolicy.js +44 -52
  103. package/dist/github/commandIdentityPolicy.js.map +7 -1
  104. package/dist/github/discovery.d.ts +1 -0
  105. package/dist/github/discovery.js +197 -215
  106. package/dist/github/discovery.js.map +7 -1
  107. package/dist/github/discovery.test.js +223 -177
  108. package/dist/github/discovery.test.js.map +7 -1
  109. package/dist/github/issueHistory.d.ts +2 -2
  110. package/dist/github/issueHistory.js +117 -125
  111. package/dist/github/issueHistory.js.map +7 -1
  112. package/dist/github/machineAuth.d.ts +1 -1
  113. package/dist/github/machineAuth.js +126 -117
  114. package/dist/github/machineAuth.js.map +7 -1
  115. package/dist/github/machineAuth.test.js +755 -639
  116. package/dist/github/machineAuth.test.js.map +7 -1
  117. package/dist/github/nativeIssueMetadata.js +286 -273
  118. package/dist/github/nativeIssueMetadata.js.map +7 -1
  119. package/dist/github/projectDelivery.d.ts +18 -2
  120. package/dist/github/projectDelivery.js +615 -557
  121. package/dist/github/projectDelivery.js.map +7 -1
  122. package/dist/github/relationships.js +433 -389
  123. package/dist/github/relationships.js.map +7 -1
  124. package/dist/github/repo.d.ts +1 -0
  125. package/dist/github/repo.js +123 -96
  126. package/dist/github/repo.js.map +7 -1
  127. package/dist/index.js +3 -3
  128. package/dist/index.js.map +7 -1
  129. package/dist/issue.d.ts +40 -9
  130. package/dist/issue.js +2102 -1742
  131. package/dist/issue.js.map +7 -1
  132. package/dist/issue63History.test.js +40 -42
  133. package/dist/issue63History.test.js.map +7 -1
  134. package/dist/issue63Routes.test.js +154 -143
  135. package/dist/issue63Routes.test.js.map +7 -1
  136. package/dist/issueBatchUpdate.test.js +989 -885
  137. package/dist/issueBatchUpdate.test.js.map +7 -1
  138. package/dist/issueBlockerGuard.test.js +262 -226
  139. package/dist/issueBlockerGuard.test.js.map +7 -1
  140. package/dist/issueContract.d.ts +23 -4
  141. package/dist/issueContract.js +416 -395
  142. package/dist/issueContract.js.map +7 -1
  143. package/dist/issueContract.test.d.ts +4 -3
  144. package/dist/issueContract.test.js +358 -321
  145. package/dist/issueContract.test.js.map +7 -1
  146. package/dist/issueDates.test.js +235 -233
  147. package/dist/issueDates.test.js.map +7 -1
  148. package/dist/issueInfoReadback.test.js +304 -190
  149. package/dist/issueInfoReadback.test.js.map +7 -1
  150. package/dist/issueIntake.test.js +1945 -1732
  151. package/dist/issueIntake.test.js.map +7 -1
  152. package/dist/issueJournal.d.ts +40 -19
  153. package/dist/issueJournal.js +229 -138
  154. package/dist/issueJournal.js.map +7 -1
  155. package/dist/issueJournal.test.js +605 -422
  156. package/dist/issueJournal.test.js.map +7 -1
  157. package/dist/issueRollup.test.d.ts +1 -0
  158. package/dist/issueRollup.test.js +476 -0
  159. package/dist/issueRollup.test.js.map +7 -0
  160. package/dist/issueTracking.test.js +1059 -989
  161. package/dist/issueTracking.test.js.map +7 -1
  162. package/dist/issueWriteRecovery.test.d.ts +1 -0
  163. package/dist/issueWriteRecovery.test.js +260 -0
  164. package/dist/issueWriteRecovery.test.js.map +7 -0
  165. package/dist/lifecycle.test.js +112 -441
  166. package/dist/lifecycle.test.js.map +7 -1
  167. package/dist/logger.js +80 -74
  168. package/dist/logger.js.map +7 -1
  169. package/dist/mcp/index.js +116 -94
  170. package/dist/mcp/index.js.map +7 -1
  171. package/dist/mcp/tools.d.ts +264 -286
  172. package/dist/mcp/tools.js +267 -340
  173. package/dist/mcp/tools.js.map +7 -1
  174. package/dist/pluginAuthProbe.js +63 -52
  175. package/dist/pluginAuthProbe.js.map +7 -1
  176. package/dist/pluginAuthProbe.test.js +85 -62
  177. package/dist/pluginAuthProbe.test.js.map +7 -1
  178. package/dist/pluginCredentials.test.js +282 -259
  179. package/dist/pluginCredentials.test.js.map +7 -1
  180. package/dist/pluginDoctor.test.js +653 -588
  181. package/dist/pluginDoctor.test.js.map +7 -1
  182. package/dist/pluginInstaller.d.ts +7 -5
  183. package/dist/pluginInstaller.js +1173 -1229
  184. package/dist/pluginInstaller.js.map +7 -1
  185. package/dist/pluginInstaller.test.js +1842 -1423
  186. package/dist/pluginInstaller.test.js.map +7 -1
  187. package/dist/pluginPackaging.test.js +460 -409
  188. package/dist/pluginPackaging.test.js.map +7 -1
  189. package/dist/pr.d.ts +132 -94
  190. package/dist/pr.js +1521 -1323
  191. package/dist/pr.js.map +7 -1
  192. package/dist/pr.test.js +1678 -632
  193. package/dist/pr.test.js.map +7 -1
  194. package/dist/prAssociation.test.js +2419 -1788
  195. package/dist/prAssociation.test.js.map +7 -1
  196. package/dist/prDispatch.test.js +150 -89
  197. package/dist/prDispatch.test.js.map +7 -1
  198. package/dist/readView.d.ts +183 -0
  199. package/dist/readView.js +217 -0
  200. package/dist/readView.js.map +7 -0
  201. package/dist/readView.test.d.ts +1 -0
  202. package/dist/readView.test.js +119 -0
  203. package/dist/readView.test.js.map +7 -0
  204. package/dist/releaseReconciliation.test.js +267 -288
  205. package/dist/releaseReconciliation.test.js.map +7 -1
  206. package/dist/releaseWorkflow.test.js +2493 -422
  207. package/dist/releaseWorkflow.test.js.map +7 -1
  208. package/dist/review.d.ts +738 -2
  209. package/dist/review.js +601 -348
  210. package/dist/review.js.map +7 -1
  211. package/dist/review.test.js +1218 -812
  212. package/dist/review.test.js.map +7 -1
  213. package/dist/reviewSubmit.test.d.ts +1 -0
  214. package/dist/reviewSubmit.test.js +747 -0
  215. package/dist/reviewSubmit.test.js.map +7 -0
  216. package/dist/services/agentReadinessService.js +42 -37
  217. package/dist/services/agentReadinessService.js.map +7 -1
  218. package/dist/services/blockerGuardService.js +188 -188
  219. package/dist/services/blockerGuardService.js.map +7 -1
  220. package/dist/services/boardReconcileService.d.ts +125 -125
  221. package/dist/services/boardReconcileService.js +1295 -1421
  222. package/dist/services/boardReconcileService.js.map +7 -1
  223. package/dist/services/deliveryAdmission.js +131 -154
  224. package/dist/services/deliveryAdmission.js.map +7 -1
  225. package/dist/services/deliveryHealthService.js +197 -199
  226. package/dist/services/deliveryHealthService.js.map +7 -1
  227. package/dist/services/legacyIssueMigration.js +263 -277
  228. package/dist/services/legacyIssueMigration.js.map +7 -1
  229. package/dist/services/worktreeRegistry.d.ts +27 -119
  230. package/dist/services/worktreeRegistry.js +765 -1182
  231. package/dist/services/worktreeRegistry.js.map +7 -1
  232. package/dist/stagedChecks.test.js +396 -194
  233. package/dist/stagedChecks.test.js.map +7 -1
  234. package/dist/start.test.js +99 -95
  235. package/dist/start.test.js.map +7 -1
  236. package/dist/stdoutRegression.test.js +353 -352
  237. package/dist/stdoutRegression.test.js.map +7 -1
  238. package/dist/targetPolicyDiscovery.test.js +141 -143
  239. package/dist/targetPolicyDiscovery.test.js.map +7 -1
  240. package/dist/targetPolicyEntrypoints.test.js +308 -269
  241. package/dist/targetPolicyEntrypoints.test.js.map +7 -1
  242. package/dist/targetPolicyLocal.test.js +580 -1051
  243. package/dist/targetPolicyLocal.test.js.map +7 -1
  244. package/dist/targetPolicyRoutes.test.js +305 -281
  245. package/dist/targetPolicyRoutes.test.js.map +7 -1
  246. package/dist/targetRepositoryExecution.test.d.ts +1 -0
  247. package/dist/targetRepositoryExecution.test.js +463 -0
  248. package/dist/targetRepositoryExecution.test.js.map +7 -0
  249. package/dist/terminalMessages.js +41 -35
  250. package/dist/terminalMessages.js.map +7 -1
  251. package/dist/toolOutput.d.ts +2 -0
  252. package/dist/toolOutput.js +36 -0
  253. package/dist/toolOutput.js.map +7 -0
  254. package/dist/toolOutput.test.d.ts +1 -0
  255. package/dist/toolOutput.test.js +240 -0
  256. package/dist/toolOutput.test.js.map +7 -0
  257. package/dist/utils/atomicJson.js +84 -76
  258. package/dist/utils/atomicJson.js.map +7 -1
  259. package/dist/utils/filesystem.js +15 -18
  260. package/dist/utils/filesystem.js.map +7 -1
  261. package/dist/utils/lockfile.js +68 -71
  262. package/dist/utils/lockfile.js.map +7 -1
  263. package/dist/verification.d.ts +1 -19
  264. package/dist/verification.js +1020 -1939
  265. package/dist/verification.js.map +7 -1
  266. package/dist/verificationGate.test.js +127 -117
  267. package/dist/verificationGate.test.js.map +7 -1
  268. package/dist/version.js +23 -24
  269. package/dist/version.js.map +7 -1
  270. package/dist/worktree.d.ts +3 -15
  271. package/dist/worktree.js +97 -177
  272. package/dist/worktree.js.map +7 -1
  273. package/package.json +9 -8
  274. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  275. package/plugins/ai-delivery/README.md +47 -156
  276. package/plugins/ai-delivery/plugin.json +1 -1
  277. package/plugins/ai-delivery/runtime/dist/THIRD-PARTY-NOTICES.md +238 -44
  278. package/plugins/ai-delivery/runtime/dist/cli.js +358 -115
  279. package/plugins/ai-delivery/runtime/package.json +1 -1
  280. package/plugins/ai-delivery/skills/intake-create/SKILL.md +14 -78
  281. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +35 -36
  282. package/plugins/ai-delivery/skills/worktree-lifecycle/SKILL.md +14 -15
  283. package/dist/investigationCompletion.test.js +0 -728
  284. package/dist/investigationCompletion.test.js.map +0 -1
  285. package/dist/setup.d.ts +0 -60
  286. package/dist/setup.js +0 -585
  287. package/dist/setup.js.map +0 -1
  288. package/dist/setup.test.js +0 -3329
  289. package/dist/setup.test.js.map +0 -1
  290. package/dist/worktreeTransition.d.ts +0 -211
  291. package/dist/worktreeTransition.js +0 -1037
  292. package/dist/worktreeTransition.js.map +0 -1
  293. package/dist/worktreeTransition.test.js +0 -1191
  294. package/dist/worktreeTransition.test.js.map +0 -1
  295. /package/dist/{investigationCompletion.test.d.ts → build.test.d.ts} +0 -0
  296. /package/dist/{setup.test.d.ts → callerErrors.test.d.ts} +0 -0
  297. /package/dist/{worktreeTransition.test.d.ts → deliveryBoard.test.d.ts} +0 -0
@@ -1,420 +1,525 @@
1
- import { createAppAuth } from '@octokit/auth-app';
2
- import { graphql } from '@octokit/graphql';
3
- import { Octokit } from '@octokit/rest';
4
- import { readFileSync } from 'node:fs';
5
- import { types } from 'node:util';
6
- import { resolveDeliveryRoleCredentials } from '../config/deliveryConfig.js';
7
- import { DeliveryError, setMachineRequestDiagnostics, getRateLimitDiagnostics, } from '../errors.js';
8
- import { assertSupportedAuthorHost, machineAuthorEligible, withMachineAuthorCredential, MACHINE_AUTH_ENV_NAMES, } from './machineAuth.js';
9
- const authorGitTokens = new WeakMap();
10
- const machineClients = new WeakSet();
11
- const machineProtectionAbsence = new WeakMap();
12
- const machineAuthorSelections = new WeakMap();
13
- const resolvedMachineAuthors = new WeakMap();
14
- /** Keep repository discovery and command execution on one resolved account. */
15
- export function retainMachineAuthorForConfiguration(config, clients, signal) {
16
- const selection = machineAuthorSelections.get(clients);
17
- if (selection !== undefined) {
18
- if (selection.signal !== signal)
19
- throw new DeliveryError('Machine GitHub session command context changed; resolve the command again.');
20
- resolvedMachineAuthors.set(config.roles, { clients, ...selection });
21
- }
1
+ import { createAppAuth } from "@octokit/auth-app";
2
+ import { graphql } from "@octokit/graphql";
3
+ import { Octokit } from "@octokit/rest";
4
+ import { closeSync, constants, fstatSync, openSync, readFileSync, readSync } from "node:fs";
5
+ import { createPrivateKey } from "node:crypto";
6
+ import { homedir } from "node:os";
7
+ import { types } from "node:util";
8
+ import {
9
+ appCredentialSource,
10
+ privateKeyVariable,
11
+ resolveDeliveryRoleCredentials
12
+ } from "../config/deliveryConfig.js";
13
+ import { runStageCommand } from "../verification.js";
14
+ import {
15
+ DeliveryError,
16
+ setMachineRequestDiagnostics,
17
+ getRateLimitDiagnostics
18
+ } from "../errors.js";
19
+ import {
20
+ assertSupportedAuthorHost,
21
+ machineAuthorEligible,
22
+ withMachineAuthorCredential,
23
+ MACHINE_AUTH_ENV_NAMES
24
+ } from "./machineAuth.js";
25
+ const authorGitTokens = /* @__PURE__ */ new WeakMap();
26
+ const machineClients = /* @__PURE__ */ new WeakSet();
27
+ const machineProtectionAbsence = /* @__PURE__ */ new WeakMap();
28
+ const machineAuthorSelections = /* @__PURE__ */ new WeakMap();
29
+ const resolvedMachineAuthors = /* @__PURE__ */ new WeakMap();
30
+ function retainMachineAuthorForConfiguration(config, clients, signal) {
31
+ const selection = machineAuthorSelections.get(clients);
32
+ if (selection !== void 0) {
33
+ if (selection.signal !== signal)
34
+ throw new DeliveryError("Machine GitHub session command context changed; resolve the command again.");
35
+ resolvedMachineAuthors.set(config.roles, { clients, ...selection });
36
+ }
22
37
  }
23
38
  function sessionSelectors(env) {
24
- return JSON.stringify(MACHINE_AUTH_ENV_NAMES.map((name) => [name, env[name]]));
39
+ return JSON.stringify(MACHINE_AUTH_ENV_NAMES.map((name) => [name, env[name]]));
25
40
  }
26
- /** Pass the selected author token only to the operation that needs Git HTTP auth. */
27
- export async function withAuthorGitToken(clients, callback) {
28
- const token = clients.role === 'author' ? authorGitTokens.get(clients) : undefined;
29
- if (!token)
30
- throw new DeliveryError('Git push requires the selected author credential token.');
31
- return callback(token);
41
+ async function withAuthorGitToken(clients, callback) {
42
+ const token = clients.role === "author" ? authorGitTokens.get(clients) : void 0;
43
+ if (!token) throw new DeliveryError("Git push requires the selected author credential token.");
44
+ return callback(token);
32
45
  }
33
- export function assertDeliveryRolePermissions(input) {
34
- if (typeof input.permissions !== 'object' || input.permissions === null || Array.isArray(input.permissions)) {
35
- throw new DeliveryError(`GitHub App ${input.role} role did not return installation permissions.`);
36
- }
37
- const permissions = input.permissions;
38
- const required = input.role === 'author'
39
- ? { contents: 'write', issues: 'write', organization_projects: 'write', pull_requests: 'write' }
40
- : { contents: 'read', pull_requests: 'write' };
41
- for (const [name, level] of [...Object.entries(required), ...Object.entries(input.additional ?? {})]) {
42
- const actual = permissions[name];
43
- if (actual !== 'admin' && actual !== 'write' && (level === 'write' || actual !== 'read')) {
44
- throw new DeliveryError(`GitHub App ${input.role} role lacks required ${name}:${level} permission.`);
45
- }
46
+ function assertDeliveryRolePermissions(input) {
47
+ if (typeof input.permissions !== "object" || input.permissions === null || Array.isArray(input.permissions)) {
48
+ throw new DeliveryError(`GitHub App ${input.role} role did not return installation permissions.`);
49
+ }
50
+ const permissions = input.permissions;
51
+ const required = input.role === "author" ? { contents: "write", issues: "write", organization_projects: "write", pull_requests: "write" } : { contents: "read", pull_requests: "write" };
52
+ for (const [name, level] of [...Object.entries(required), ...Object.entries(input.additional ?? {})]) {
53
+ const actual = permissions[name];
54
+ if (actual !== "admin" && actual !== "write" && (level === "write" || actual !== "read")) {
55
+ throw new DeliveryError(`GitHub App ${input.role} role lacks required ${name}:${level} permission.`);
46
56
  }
57
+ }
47
58
  }
48
- /** The author role may use a personal token only after an explicit operator opt-in. */
49
- export async function createDeliveryGitHubClients(input) {
50
- input.signal?.throwIfAborted();
51
- const env = input.env ?? process.env;
52
- const selected = input.config.roles[input.role];
53
- const retained = input.role === 'author' ? resolvedMachineAuthors.get(input.config.roles) : undefined;
54
- if (retained !== undefined) {
55
- // A command that discovered its repository as account A must not acquire
56
- // a newly supplied token/profile and then operate as account B.
57
- if (selected.authSource !== 'personal' ||
58
- input.identity.trim().toLowerCase() !== selected.identity.toLowerCase() ||
59
- !machineAuthorEligible(selected.credentialEnv.token, env) ||
60
- retained.env !== env ||
61
- retained.signal !== input.signal ||
62
- retained.selectors !== sessionSelectors(env))
63
- throw new DeliveryError('Machine GitHub session environment changed after repository selection; resolve the command again.');
64
- assertSupportedAuthorHost(env);
65
- return retained.clients;
59
+ async function createDeliveryGitHubClients(input) {
60
+ input.signal?.throwIfAborted();
61
+ const env = input.env ?? process.env;
62
+ const selected = input.config.roles[input.role];
63
+ const retained = input.role === "author" ? resolvedMachineAuthors.get(input.config.roles) : void 0;
64
+ if (retained !== void 0) {
65
+ if (selected.authSource !== "personal" || input.identity.trim().toLowerCase() !== selected.identity.toLowerCase() || !machineAuthorEligible(selected.credentialEnv.token, env) || retained.env !== env || retained.signal !== input.signal || retained.selectors !== sessionSelectors(env))
66
+ throw new DeliveryError(
67
+ "Machine GitHub session environment changed after repository selection; resolve the command again."
68
+ );
69
+ assertSupportedAuthorHost(env);
70
+ return retained.clients;
71
+ }
72
+ if (selected.authSource === "personal") {
73
+ if (input.role !== "author" || input.identity.trim().toLowerCase() !== selected.identity.toLowerCase()) {
74
+ throw new DeliveryError("Personal author operation requires the configured author identity.");
66
75
  }
67
- if (selected.authSource === 'personal') {
68
- if (input.role !== 'author' || input.identity.trim().toLowerCase() !== selected.identity.toLowerCase()) {
69
- throw new DeliveryError('Personal author operation requires the configured author identity.');
70
- }
71
- assertSupportedAuthorHost(env);
72
- if (machineAuthorEligible(selected.credentialEnv.token, env)) {
73
- const selection = { env, signal: input.signal, selectors: sessionSelectors(env) };
74
- return withMachineAuthorCredential(env, input.signal, async (token, session) => {
75
- const clients = personalClients(token, `gh:github.com:${session.executable}`, input.signal, session.login);
76
- await clients.authenticatedAuthor(input.signal);
77
- machineAuthorSelections.set(clients, selection);
78
- return clients;
79
- });
80
- }
81
- const token = env[selected.credentialEnv.token]?.trim();
82
- if (!token) {
83
- throw new DeliveryError(`Missing personal author token in ${selected.credentialEnv.token}.`);
84
- }
85
- return personalClients(token, `env:${selected.credentialEnv.token}`, input.signal);
76
+ assertSupportedAuthorHost(env);
77
+ if (machineAuthorEligible(selected.credentialEnv.token, env)) {
78
+ const selection = { env, signal: input.signal, selectors: sessionSelectors(env) };
79
+ return withMachineAuthorCredential(env, input.signal, async (token2, session) => {
80
+ const clients = personalClients(token2, `gh:github.com:${session.executable}`, input.signal, session.login);
81
+ await clients.authenticatedAuthor(input.signal);
82
+ machineAuthorSelections.set(clients, selection);
83
+ return clients;
84
+ });
86
85
  }
87
- if (input.personalAuth !== undefined) {
88
- if (input.personalAuth.enabled !== true ||
89
- input.role !== 'author' ||
90
- input.identity.trim().toLowerCase() !== 'personal') {
91
- throw new DeliveryError('Personal-token auth requires the explicit personal author identity.');
92
- }
93
- assertSupportedAuthorHost(env);
94
- const token = (input.personalAuth.token ?? env.GH_TOKEN ?? env.GITHUB_TOKEN)?.trim();
95
- if (!token)
96
- throw new DeliveryError('Explicit personal-token auth requested but no token was supplied.');
97
- const source = input.personalAuth.token !== undefined
98
- ? 'explicit-personal-token'
99
- : env.GH_TOKEN !== undefined
100
- ? 'env:GH_TOKEN'
101
- : 'env:GITHUB_TOKEN';
102
- return personalClients(token, source, input.signal);
86
+ const token = env[selected.credentialEnv.token]?.trim();
87
+ if (!token) {
88
+ throw new DeliveryError(`Missing personal author token in ${selected.credentialEnv.token}.`);
103
89
  }
104
- if (input.identity.trim().toLowerCase() !== selected.identity.toLowerCase()) {
105
- throw new DeliveryError(`GitHub ${input.role} operation requires the configured ${input.role} identity.`);
90
+ return personalClients(token, `env:${selected.credentialEnv.token}`, input.signal);
91
+ }
92
+ if (input.personalAuth !== void 0) {
93
+ if (input.personalAuth.enabled !== true || input.role !== "author" || input.identity.trim().toLowerCase() !== "personal") {
94
+ throw new DeliveryError("Personal-token auth requires the explicit personal author identity.");
106
95
  }
107
- const credentials = resolveDeliveryRoleCredentials({ config: input.config, env, role: input.role });
108
- const otherRole = input.role === 'author' ? 'reviewer' : 'author';
109
- const personalAuthorSelected = input.role === 'reviewer' &&
110
- input.selectedAuthor?.role === 'author' &&
111
- input.selectedAuthor.authSource === 'personal';
112
- if (!personalAuthorSelected && input.config.roles[otherRole].authSource !== 'personal') {
113
- const other = resolveDeliveryRoleCredentials({ config: input.config, env, role: otherRole });
114
- if (credentials.appId === other.appId ||
115
- credentials.installationId === other.installationId ||
116
- credentials.privateKeyPath === other.privateKeyPath) {
117
- throw new DeliveryError('Author and reviewer must use distinct GitHub App credentials.');
118
- }
96
+ assertSupportedAuthorHost(env);
97
+ const token = (input.personalAuth.token ?? env.GH_TOKEN ?? env.GITHUB_TOKEN)?.trim();
98
+ if (!token) throw new DeliveryError("Explicit personal-token auth requested but no token was supplied.");
99
+ const source = input.personalAuth.token !== void 0 ? "explicit-personal-token" : env.GH_TOKEN !== void 0 ? "env:GH_TOKEN" : "env:GITHUB_TOKEN";
100
+ return personalClients(token, source, input.signal);
101
+ }
102
+ if (input.identity.trim().toLowerCase() !== selected.identity.toLowerCase()) {
103
+ throw new DeliveryError(`GitHub ${input.role} operation requires the configured ${input.role} identity.`);
104
+ }
105
+ const credentials = resolveDeliveryRoleCredentials({ config: input.config, env, role: input.role });
106
+ const otherRole = input.role === "author" ? "reviewer" : "author";
107
+ const personalAuthorSelected = input.role === "reviewer" && input.selectedAuthor?.role === "author" && input.selectedAuthor.authSource === "personal";
108
+ if (!personalAuthorSelected && input.config.roles[otherRole].authSource !== "personal") {
109
+ const otherRoleConfig = input.config.roles[otherRole];
110
+ const other = credentials.profile === void 0 ? resolveDeliveryRoleCredentials({ config: input.config, env, role: otherRole }) : "appId" in otherRoleConfig ? {
111
+ appId: String(otherRoleConfig.appId),
112
+ installationId: otherRoleConfig.installationId,
113
+ privateKeyPath: void 0
114
+ } : {
115
+ appId: env[otherRoleConfig.credentialEnv.appId]?.trim(),
116
+ installationId: Number(env[otherRoleConfig.credentialEnv.installationId]),
117
+ privateKeyPath: void 0
118
+ };
119
+ if (credentials.appId === other.appId || credentials.installationId === other.installationId || credentials.privateKeyPath !== void 0 && credentials.privateKeyPath === other.privateKeyPath) {
120
+ throw new DeliveryError("Author and reviewer must use distinct GitHub App credentials.");
119
121
  }
120
- let privateKey;
122
+ }
123
+ let privateKey;
124
+ if (credentials.profile !== void 0) {
125
+ privateKey = await selectedPrivateKey(credentials.profile, env, input.config, input.signal);
126
+ } else {
121
127
  try {
122
- privateKey = readFileSync(credentials.privateKeyPath, 'utf8');
128
+ privateKey = readFileSync(credentials.privateKeyPath, "utf8");
129
+ } catch {
130
+ throw new DeliveryError(`GitHub App private key for ${input.role} role is unavailable.`);
123
131
  }
124
- catch {
125
- throw new DeliveryError(`GitHub App private key for ${input.role} role is unavailable.`);
132
+ }
133
+ try {
134
+ const auth = createAppAuth({
135
+ appId: credentials.appId,
136
+ privateKey,
137
+ ...input.signal === void 0 ? {} : { request: new Octokit({ request: { signal: input.signal } }).request }
138
+ });
139
+ const result = await auth({ installationId: credentials.installationId, type: "installation" });
140
+ if (typeof result.token !== "string" || !result.token.startsWith("ghs_")) {
141
+ throw new DeliveryError(`GitHub ${input.role} role did not receive an App installation token.`);
126
142
  }
127
- try {
128
- const auth = createAppAuth({
129
- appId: credentials.appId,
130
- privateKey,
131
- ...(input.signal === undefined ? {} : { request: new Octokit({ request: { signal: input.signal } }).request }),
132
- });
133
- const result = await auth({ installationId: credentials.installationId, type: 'installation' });
134
- if (typeof result.token !== 'string' || !result.token.startsWith('ghs_')) {
135
- throw new DeliveryError(`GitHub ${input.role} role did not receive an App installation token.`);
143
+ assertDeliveryRolePermissions({
144
+ ...input.additionalPermissions === void 0 ? {} : { additional: input.additionalPermissions },
145
+ permissions: result.permissions,
146
+ role: input.role
147
+ });
148
+ const appActorLogin = input.role === "reviewer" ? async (signal) => {
149
+ const requestSignal = signal ?? input.signal;
150
+ try {
151
+ const app = await new Octokit({
152
+ auth: (await auth({ type: "app" })).token,
153
+ ...requestSignal === void 0 ? {} : { request: { signal: requestSignal } }
154
+ }).rest.apps.getAuthenticated();
155
+ if (!app.data || app.data.id !== Number(credentials.appId) || !app.data.slug) {
156
+ throw new DeliveryError("Reviewer GitHub App identity did not match its configured App ID.");
136
157
  }
137
- assertDeliveryRolePermissions({
138
- ...(input.additionalPermissions === undefined ? {} : { additional: input.additionalPermissions }),
139
- permissions: result.permissions,
140
- role: input.role,
141
- });
142
- const appActorLogin = input.role === 'reviewer'
143
- ? async (signal) => {
144
- const requestSignal = signal ?? input.signal;
145
- try {
146
- const app = await new Octokit({
147
- auth: (await auth({ type: 'app' })).token,
148
- ...(requestSignal === undefined ? {} : { request: { signal: requestSignal } }),
149
- }).rest.apps.getAuthenticated();
150
- if (!app.data || app.data.id !== Number(credentials.appId) || !app.data.slug) {
151
- throw new DeliveryError('Reviewer GitHub App identity did not match its configured App ID.');
152
- }
153
- return `${app.data.slug}[bot]`;
154
- }
155
- catch (error) {
156
- if (error instanceof DeliveryError)
157
- throw error;
158
- throw new DeliveryError('Reviewer GitHub App actor lookup failed.');
159
- }
160
- }
161
- : undefined;
162
- const authenticatedAuthor = input.role === 'author'
163
- ? async (signal) => {
164
- const requestSignal = signal ?? input.signal;
165
- try {
166
- const app = await new Octokit({
167
- auth: (await auth({ type: 'app' })).token,
168
- ...(requestSignal === undefined ? {} : { request: { signal: requestSignal } }),
169
- }).rest.apps.getAuthenticated();
170
- if (!app.data || app.data.id !== Number(credentials.appId) || !app.data.slug) {
171
- throw new DeliveryError('Author GitHub App identity did not match its configured App ID.');
172
- }
173
- return {
174
- actorLogin: `${app.data.slug}[bot]`,
175
- credentialIdentity: `app:${String(app.data.id)}:installation:${credentials.installationId}`,
176
- };
177
- }
178
- catch (error) {
179
- if (error instanceof DeliveryError)
180
- throw error;
181
- throw new DeliveryError('Author GitHub App actor lookup failed.');
182
- }
158
+ const actor = `${app.data.slug}[bot]`;
159
+ if (credentials.profile !== void 0 && actor !== credentials.profile.actorLogin)
160
+ throw new DeliveryError("Reviewer GitHub App actor did not match its configured actorLogin.");
161
+ return actor;
162
+ } catch (error) {
163
+ if (error instanceof DeliveryError) throw error;
164
+ throw new DeliveryError("Reviewer GitHub App actor lookup failed.");
165
+ }
166
+ } : void 0;
167
+ const authenticatedAuthor = input.role === "author" ? async (signal) => {
168
+ const requestSignal = signal ?? input.signal;
169
+ try {
170
+ const app = await new Octokit({
171
+ auth: (await auth({ type: "app" })).token,
172
+ ...requestSignal === void 0 ? {} : { request: { signal: requestSignal } }
173
+ }).rest.apps.getAuthenticated();
174
+ if (!app.data || app.data.id !== Number(credentials.appId) || !app.data.slug) {
175
+ throw new DeliveryError("Author GitHub App identity did not match its configured App ID.");
176
+ }
177
+ return {
178
+ actorLogin: `${app.data.slug}[bot]`,
179
+ credentialIdentity: `app:${String(app.data.id)}:installation:${credentials.installationId}`
180
+ };
181
+ } catch (error) {
182
+ if (error instanceof DeliveryError) throw error;
183
+ throw new DeliveryError("Author GitHub App actor lookup failed.");
184
+ }
185
+ } : void 0;
186
+ return buildClients(
187
+ result.token,
188
+ "app",
189
+ input.role,
190
+ `app:${credentials.appId}:installation:${credentials.installationId}`,
191
+ appActorLogin,
192
+ authenticatedAuthor,
193
+ result.permissions.contents,
194
+ input.signal
195
+ );
196
+ } catch (error) {
197
+ input.signal?.throwIfAborted();
198
+ if (error instanceof DeliveryError) throw error;
199
+ throw new DeliveryError(`GitHub App authentication failed for ${input.role} role.`);
200
+ }
201
+ }
202
+ async function selectedPrivateKey(profile, env, config, signal) {
203
+ const source = appCredentialSource(profile);
204
+ const failure = (reason) => new DeliveryError(`Reviewer ${profile.identity} credential source ${source.type}: ${reason}`);
205
+ let bytes;
206
+ try {
207
+ signal?.throwIfAborted();
208
+ if (source.type === "env") {
209
+ const value = env[privateKeyVariable(profile)];
210
+ if (!value) throw failure("selected variable is missing or empty; configure this identity.");
211
+ if (Buffer.byteLength(value) > 64 * 1024) throw failure("response exceeds 64 KiB.");
212
+ bytes = Buffer.from(value);
213
+ } else if (source.type === "file") {
214
+ const fd = openSync(source.path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
215
+ try {
216
+ const stat = fstatSync(fd);
217
+ if (!stat.isFile() || (stat.mode & 4095) !== 384 || stat.nlink !== 1 || process.getuid !== void 0 && stat.uid !== process.getuid())
218
+ throw failure("key file must be a regular, owned, single-link file with mode 0600.");
219
+ const buffer = Buffer.alloc(64 * 1024 + 1);
220
+ let size = 0;
221
+ for (; ; ) {
222
+ const read = readSync(fd, buffer, size, buffer.length - size, null);
223
+ if (read === 0) break;
224
+ size += read;
225
+ if (size === buffer.length) throw failure("response exceeds 64 KiB.");
226
+ }
227
+ bytes = buffer.subarray(0, size);
228
+ } finally {
229
+ closeSync(fd);
230
+ }
231
+ } else {
232
+ if (process.platform === "win32")
233
+ throw failure("command sources currently require a POSIX process supervisor; use env on Windows.");
234
+ const commandEnv = {};
235
+ const forbidden = /* @__PURE__ */ new Set([
236
+ ...config.credentialKeyReferences ?? [],
237
+ ...Object.values(config.roles).flatMap(
238
+ (role) => "credentialEnv" in role ? Object.values(role.credentialEnv) : appCredentialSource(role).type === "env" ? [privateKeyVariable(role)] : []
239
+ )
240
+ ]);
241
+ for (const name of [
242
+ "HOME",
243
+ "USER",
244
+ "LOGNAME",
245
+ "PATH",
246
+ "LANG",
247
+ "LC_ALL",
248
+ "TMPDIR",
249
+ "TEMP",
250
+ "TMP",
251
+ "SystemRoot",
252
+ "USERPROFILE",
253
+ "APPDATA",
254
+ "LOCALAPPDATA"
255
+ ]) {
256
+ if (forbidden.has(name)) throw failure("credential reference conflicts with an implicit OS selector.");
257
+ if (env[name] !== void 0) commandEnv[name] = env[name];
258
+ }
259
+ for (const name of source.env ?? []) {
260
+ if (forbidden.has(name) || /^(?:NODE_|NPM_|DYLD_|LD_|BASH_|GIT_|GH_PRIVATE_KEY)/u.test(name) || ["ENV", "SHELLOPTS", "CDPATH"].includes(name))
261
+ throw failure("helper environment reference conflicts with author/key or execution selectors.");
262
+ if (env[name] === void 0) throw failure("a configured helper environment reference is missing.");
263
+ commandEnv[name] = env[name];
264
+ }
265
+ const timeout = new AbortController();
266
+ const timer = setTimeout(() => timeout.abort(), 3e4);
267
+ let cleanupFailed = false;
268
+ try {
269
+ bytes = await runStageCommand(
270
+ env.HOME ?? homedir(),
271
+ source.argv,
272
+ signal === void 0 ? timeout.signal : AbortSignal.any([signal, timeout.signal]),
273
+ void 0,
274
+ void 0,
275
+ void 0,
276
+ void 0,
277
+ void 0,
278
+ {
279
+ environment: commandEnv,
280
+ cwd: env.HOME ?? homedir(),
281
+ maxCapturedOutputBytes: 64 * 1024,
282
+ stdoutOnly: true,
283
+ failedOutput: () => "",
284
+ onCleanupFailure: () => {
285
+ cleanupFailed = true;
183
286
  }
184
- : undefined;
185
- return buildClients(result.token, 'app', input.role, `app:${credentials.appId}:installation:${credentials.installationId}`, appActorLogin, authenticatedAuthor, result.permissions.contents, input.signal);
287
+ }
288
+ );
289
+ } catch {
290
+ throw failure(
291
+ cleanupFailed ? "helper failed and owned process cleanup is unverified; reconcile before retrying." : timeout.signal.aborted ? "helper response timed out; verify the selected command." : signal?.aborted ? "helper request cancelled." : "helper failed; verify its executable, access and bounded output."
292
+ );
293
+ } finally {
294
+ clearTimeout(timer);
295
+ }
186
296
  }
187
- catch (error) {
188
- if (error instanceof DeliveryError)
189
- throw error;
190
- throw new DeliveryError(`GitHub App authentication failed for ${input.role} role.`);
297
+ if (bytes.length === 0 || bytes.length > 64 * 1024) throw failure("response is empty or exceeds 64 KiB.");
298
+ let pem = bytes.toString("utf8");
299
+ if (!Buffer.from(pem).equals(bytes)) throw failure("response must be valid UTF-8.");
300
+ if (source.type !== "file" && source.encoding === "base64") {
301
+ const encoded = pem.trim();
302
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(encoded))
303
+ throw failure("response must be canonical base64.");
304
+ const decoded = Buffer.from(encoded, "base64");
305
+ if (decoded.toString("base64") !== encoded) throw failure("response must be canonical base64.");
306
+ pem = decoded.toString("utf8");
307
+ if (!Buffer.from(pem).equals(decoded)) throw failure("decoded response must be UTF-8 PEM.");
191
308
  }
309
+ if (!/^-----BEGIN (?:RSA )?PRIVATE KEY-----\r?\n[\s\S]+\r?\n-----END (?:RSA )?PRIVATE KEY-----\s*$/u.test(pem) || createPrivateKey(pem).asymmetricKeyType !== "rsa")
310
+ throw failure("response must be an unencrypted RSA private key in PEM format.");
311
+ signal?.throwIfAborted();
312
+ return pem;
313
+ } catch (error) {
314
+ if (error instanceof DeliveryError) throw error;
315
+ throw failure("selected key is unavailable or malformed; verify this source.");
316
+ }
192
317
  }
193
318
  function personalClients(token, credentialSource, signal, machineLogin) {
194
- if (!/^[A-Za-z0-9_-]{1,4096}$/u.test(token))
195
- throw new DeliveryError('Selected personal author token is malformed; verify the explicit credential.');
196
- if (machineLogin !== undefined && (credentialSource.includes(token) || machineLogin.includes(token)))
197
- throw new DeliveryError('Machine GitHub session readback is unsafe.');
198
- return buildClients(token, 'personal', 'author', credentialSource, undefined, async (requestSignal) => {
199
- const selectedSignal = requestSignal ?? signal;
200
- try {
201
- const user = (await new Octokit({
202
- auth: token,
203
- ...(machineLogin === undefined ? {} : { log: { debug() { }, info() { }, warn() { }, error() { } } }),
204
- ...(selectedSignal === undefined ? {} : { request: { signal: selectedSignal } }),
205
- }).rest.users.getAuthenticated()).data;
206
- if (!Number.isSafeInteger(user.id) || user.id <= 0 || !user.login) {
207
- throw new DeliveryError('Personal author identity readback is incomplete.');
208
- }
209
- if (machineLogin !== undefined &&
210
- (user.type !== 'User' ||
211
- user.login.toLowerCase() !== machineLogin.toLowerCase() ||
212
- !/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u.test(user.login) ||
213
- user.login.includes(token)))
214
- throw new DeliveryError('Machine GitHub session identity does not match the selected active account.');
215
- return { actorLogin: user.login, credentialIdentity: `user:${String(user.id)}` };
319
+ if (!/^[A-Za-z0-9_-]{1,4096}$/u.test(token))
320
+ throw new DeliveryError("Selected personal author token is malformed; verify the explicit credential.");
321
+ if (machineLogin !== void 0 && (credentialSource.includes(token) || machineLogin.includes(token)))
322
+ throw new DeliveryError("Machine GitHub session readback is unsafe.");
323
+ return buildClients(
324
+ token,
325
+ "personal",
326
+ "author",
327
+ credentialSource,
328
+ void 0,
329
+ async (requestSignal) => {
330
+ const selectedSignal = requestSignal ?? signal;
331
+ try {
332
+ const user = (await new Octokit({
333
+ auth: token,
334
+ ...machineLogin === void 0 ? {} : { log: { debug() {
335
+ }, info() {
336
+ }, warn() {
337
+ }, error() {
338
+ } } },
339
+ ...selectedSignal === void 0 ? {} : { request: { signal: selectedSignal } }
340
+ }).rest.users.getAuthenticated()).data;
341
+ if (!Number.isSafeInteger(user.id) || user.id <= 0 || !user.login) {
342
+ throw new DeliveryError("Personal author identity readback is incomplete.");
216
343
  }
217
- catch (error) {
218
- if (error instanceof DeliveryError)
219
- throw error;
220
- if (error.status === 401) {
221
- throw new DeliveryError(machineLogin === undefined
222
- ? 'Configured personal author token is invalid or expired; refresh the selected token.'
223
- : 'Machine GitHub session is invalid or expired; verify the selected github.com account.');
224
- }
225
- throw new DeliveryError('Personal author identity readback failed.');
344
+ if (machineLogin !== void 0 && (user.type !== "User" || user.login.toLowerCase() !== machineLogin.toLowerCase() || !/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u.test(user.login) || user.login.includes(token)))
345
+ throw new DeliveryError("Machine GitHub session identity does not match the selected active account.");
346
+ return { actorLogin: user.login, credentialIdentity: `user:${String(user.id)}` };
347
+ } catch (error) {
348
+ if (error instanceof DeliveryError) throw error;
349
+ if (error.status === 401) {
350
+ throw new DeliveryError(
351
+ machineLogin === void 0 ? "Configured personal author token is invalid or expired; refresh the selected token." : "Machine GitHub session is invalid or expired; verify the selected github.com account."
352
+ );
226
353
  }
227
- }, undefined, signal, machineLogin !== undefined);
354
+ throw new DeliveryError("Personal author identity readback failed.");
355
+ }
356
+ },
357
+ void 0,
358
+ signal,
359
+ machineLogin !== void 0
360
+ );
228
361
  }
229
362
  function buildClients(token, authSource, role, credentialSource, appActorLogin, authenticatedAuthor, effectiveContentsPermission, signal, machineSession = false) {
230
- const rest = new Octokit({
231
- auth: token,
232
- ...(machineSession ? { log: { debug() { }, info() { }, warn() { }, error() { } } } : {}),
233
- ...(signal === undefined ? {} : { request: { signal } }),
234
- });
235
- const rawGraphql = graphql.defaults({
236
- headers: { authorization: `token ${token}` },
237
- ...(signal === undefined ? {} : { request: { signal } }),
238
- });
239
- let observedRateLimit;
240
- const observeRateLimit = (error, graphqlFailure = false) => {
241
- observedRateLimit = getRateLimitDiagnostics(error, graphqlFailure) ?? observedRateLimit;
242
- };
243
- rest.hook.error('request', (error) => {
244
- observeRateLimit(error);
245
- throw error;
363
+ const rest = new Octokit({
364
+ auth: token,
365
+ ...machineSession ? { log: { debug() {
366
+ }, info() {
367
+ }, warn() {
368
+ }, error() {
369
+ } } } : {},
370
+ ...signal === void 0 ? {} : { request: { signal } }
371
+ });
372
+ const rawGraphql = graphql.defaults({
373
+ headers: { authorization: `token ${token}` },
374
+ ...signal === void 0 ? {} : { request: { signal } }
375
+ });
376
+ let observedRateLimit;
377
+ const observeRateLimit = (error, graphqlFailure = false) => {
378
+ observedRateLimit = getRateLimitDiagnostics(error, graphqlFailure) ?? observedRateLimit;
379
+ };
380
+ rest.hook.error("request", (error) => {
381
+ observeRateLimit(error);
382
+ throw error;
383
+ });
384
+ if (machineSession)
385
+ rest.hook.error("request", (error, options) => {
386
+ const safe = safeMachineRequestError(error, "rest.request", restMachineEndpoint(options));
387
+ const target = branchProtectionTarget(options);
388
+ const responseTarget = branchProtectionTarget({ method: "GET", url: ownData(ownData(error, "response"), "url") });
389
+ if (target && responseTarget && target.owner.toLowerCase() === responseTarget.owner.toLowerCase() && target.repo.toLowerCase() === responseTarget.repo.toLowerCase() && target.branch === responseTarget.branch && exactBranchProtectionAbsence(error))
390
+ machineProtectionAbsence.set(safe, { clients, ...target });
391
+ throw safe;
246
392
  });
247
- if (machineSession)
248
- rest.hook.error('request', (error, options) => {
249
- const safe = safeMachineRequestError(error, 'rest.request', restMachineEndpoint(options));
250
- const target = branchProtectionTarget(options);
251
- const responseTarget = branchProtectionTarget({ method: 'GET', url: ownData(ownData(error, 'response'), 'url') });
252
- if (target &&
253
- responseTarget &&
254
- target.owner.toLowerCase() === responseTarget.owner.toLowerCase() &&
255
- target.repo.toLowerCase() === responseTarget.repo.toLowerCase() &&
256
- target.branch === responseTarget.branch &&
257
- exactBranchProtectionAbsence(error))
258
- machineProtectionAbsence.set(safe, { clients, ...target });
259
- throw safe;
393
+ const clients = {
394
+ authSource,
395
+ credentialSource,
396
+ ...effectiveContentsPermission ? { effectiveContentsPermission } : {},
397
+ role,
398
+ ...appActorLogin ? { appActorLogin } : {},
399
+ ...authenticatedAuthor ? { authenticatedAuthor } : {},
400
+ graphql: new Proxy(rawGraphql, {
401
+ apply(target, receiver, args) {
402
+ return Reflect.apply(target, receiver, args).catch((error) => {
403
+ observeRateLimit(error, true);
404
+ throw machineSession ? safeMachineRequestError(error, "graphql.request", "graphql") : error;
260
405
  });
261
- const clients = {
262
- authSource,
263
- credentialSource,
264
- ...(effectiveContentsPermission ? { effectiveContentsPermission } : {}),
265
- role,
266
- ...(appActorLogin ? { appActorLogin } : {}),
267
- ...(authenticatedAuthor ? { authenticatedAuthor } : {}),
268
- graphql: new Proxy(rawGraphql, {
269
- apply(target, receiver, args) {
270
- return Reflect.apply(target, receiver, args).catch((error) => {
271
- observeRateLimit(error, true);
272
- throw machineSession ? safeMachineRequestError(error, 'graphql.request', 'graphql') : error;
273
- });
274
- },
275
- }),
276
- rest,
277
- rateLimitObservation: () => observedRateLimit,
278
- };
279
- if (machineSession)
280
- machineClients.add(clients);
281
- if (role === 'author')
282
- authorGitTokens.set(clients, token);
283
- return clients;
406
+ }
407
+ }),
408
+ rest,
409
+ rateLimitObservation: () => observedRateLimit
410
+ };
411
+ if (machineSession) machineClients.add(clients);
412
+ if (role === "author") authorGitTokens.set(clients, token);
413
+ return clients;
284
414
  }
285
415
  function ownData(value, name) {
286
- if (typeof value !== 'object' || value === null || types.isProxy(value) || Array.isArray(value))
287
- return undefined;
288
- const descriptor = Object.getOwnPropertyDescriptor(value, name);
289
- return descriptor && 'value' in descriptor ? descriptor.value : undefined;
416
+ if (typeof value !== "object" || value === null || types.isProxy(value) || Array.isArray(value)) return void 0;
417
+ const descriptor = Object.getOwnPropertyDescriptor(value, name);
418
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
290
419
  }
291
420
  function exactBranchProtectionAbsence(error) {
292
- const response = ownData(error, 'response');
293
- return (ownData(error, 'status') === 404 &&
294
- ownData(response, 'status') === 404 &&
295
- ownData(ownData(response, 'data'), 'message') === 'Branch not protected');
421
+ const response = ownData(error, "response");
422
+ return ownData(error, "status") === 404 && ownData(response, "status") === 404 && ownData(ownData(response, "data"), "message") === "Branch not protected";
296
423
  }
297
424
  function branchProtectionTarget(options) {
298
- const url = ownData(options, 'url');
299
- if (ownData(options, 'method') !== 'GET' || typeof url !== 'string' || url.length > 1024 || /[^\x21-\x7e]/u.test(url))
300
- return undefined;
301
- let path;
302
- if (url.startsWith('/')) {
303
- if (ownData(options, 'baseUrl') !== 'https://api.github.com' || /[?#]/u.test(url))
304
- return undefined;
305
- path = url;
306
- }
307
- else {
308
- try {
309
- const parsed = new URL(url);
310
- if (parsed.origin !== 'https://api.github.com' ||
311
- parsed.username ||
312
- parsed.password ||
313
- parsed.search ||
314
- parsed.hash)
315
- return undefined;
316
- path = parsed.pathname;
317
- }
318
- catch {
319
- return undefined;
320
- }
321
- }
322
- let owner, repo, branch;
323
- if (path === '/repos/{owner}/{repo}/branches/{branch}/protection') {
324
- owner = ownData(options, 'owner');
325
- repo = ownData(options, 'repo');
326
- branch = ownData(options, 'branch');
425
+ const url = ownData(options, "url");
426
+ if (ownData(options, "method") !== "GET" || typeof url !== "string" || url.length > 1024 || /[^\x21-\x7e]/u.test(url))
427
+ return void 0;
428
+ let path;
429
+ if (url.startsWith("/")) {
430
+ if (ownData(options, "baseUrl") !== "https://api.github.com" || /[?#]/u.test(url)) return void 0;
431
+ path = url;
432
+ } else {
433
+ try {
434
+ const parsed = new URL(url);
435
+ if (parsed.origin !== "https://api.github.com" || parsed.username || parsed.password || parsed.search || parsed.hash)
436
+ return void 0;
437
+ path = parsed.pathname;
438
+ } catch {
439
+ return void 0;
327
440
  }
328
- else {
329
- const match = /^\/repos\/([^/]+)\/([^/]+)\/branches\/(.+)\/protection$/u.exec(path);
330
- if (!match)
331
- return undefined;
332
- try {
333
- [owner, repo, branch] = match.slice(1).map((part) => decodeURIComponent(part));
334
- }
335
- catch {
336
- return undefined;
337
- }
441
+ }
442
+ let owner, repo, branch;
443
+ if (path === "/repos/{owner}/{repo}/branches/{branch}/protection") {
444
+ owner = ownData(options, "owner");
445
+ repo = ownData(options, "repo");
446
+ branch = ownData(options, "branch");
447
+ } else {
448
+ const match = /^\/repos\/([^/]+)\/([^/]+)\/branches\/(.+)\/protection$/u.exec(path);
449
+ if (!match) return void 0;
450
+ try {
451
+ [owner, repo, branch] = match.slice(1).map((part) => decodeURIComponent(part));
452
+ } catch {
453
+ return void 0;
338
454
  }
339
- if (typeof owner !== 'string' ||
340
- !/^[A-Za-z0-9_-]{1,100}$/u.test(owner) ||
341
- typeof repo !== 'string' ||
342
- !/^[A-Za-z0-9_.-]{1,100}$/u.test(repo) ||
343
- typeof branch !== 'string' ||
344
- !branch.length ||
345
- branch.length > 1024 ||
346
- /[^\x21-\x7e]/u.test(branch))
347
- return undefined;
348
- return { owner, repo, branch };
455
+ }
456
+ if (typeof owner !== "string" || !/^[A-Za-z0-9_-]{1,100}$/u.test(owner) || typeof repo !== "string" || !/^[A-Za-z0-9_.-]{1,100}$/u.test(repo) || typeof branch !== "string" || !branch.length || branch.length > 1024 || /[^\x21-\x7e]/u.test(branch))
457
+ return void 0;
458
+ return { owner, repo, branch };
349
459
  }
350
- /** Internal read-only predicate: machine absence never comes from copied error fields. */
351
- export function hasBranchProtectionAbsence(error, clients, repository, branch) {
352
- if (!machineClients.has(clients))
353
- return exactBranchProtectionAbsence(error);
354
- if (typeof error !== 'object' || error === null || types.isProxy(error))
355
- return false;
356
- const target = machineProtectionAbsence.get(error);
357
- return (target?.clients === clients &&
358
- target.owner.toLowerCase() === repository.owner.toLowerCase() &&
359
- target.repo.toLowerCase() === repository.repo.toLowerCase() &&
360
- target.branch === branch);
460
+ function hasBranchProtectionAbsence(error, clients, repository, branch) {
461
+ if (!machineClients.has(clients)) return exactBranchProtectionAbsence(error);
462
+ if (typeof error !== "object" || error === null || types.isProxy(error)) return false;
463
+ const target = machineProtectionAbsence.get(error);
464
+ return target?.clients === clients && target.owner.toLowerCase() === repository.owner.toLowerCase() && target.repo.toLowerCase() === repository.repo.toLowerCase() && target.branch === branch;
361
465
  }
362
466
  function restMachineEndpoint(options) {
363
- const method = ownData(options, 'method'), url = ownData(options, 'url');
364
- if (typeof method !== 'string' || typeof url !== 'string' || url.length > 1024 || /[^\x21-\x7e]/u.test(url))
365
- return 'UNKNOWN';
366
- let path;
367
- if (url.startsWith('/')) {
368
- const base = ownData(options, 'baseUrl');
369
- if (base !== 'https://api.github.com')
370
- return 'UNKNOWN';
371
- path = url.split(/[?#]/u)[0];
372
- }
373
- else {
374
- try {
375
- const parsed = new URL(url);
376
- if (parsed.origin !== 'https://api.github.com' || parsed.username || parsed.password)
377
- return 'UNKNOWN';
378
- path = parsed.pathname;
379
- }
380
- catch {
381
- return 'UNKNOWN';
382
- }
467
+ const method = ownData(options, "method"), url = ownData(options, "url");
468
+ if (typeof method !== "string" || typeof url !== "string" || url.length > 1024 || /[^\x21-\x7e]/u.test(url))
469
+ return "UNKNOWN";
470
+ let path;
471
+ if (url.startsWith("/")) {
472
+ const base = ownData(options, "baseUrl");
473
+ if (base !== "https://api.github.com") return "UNKNOWN";
474
+ path = url.split(/[?#]/u)[0];
475
+ } else {
476
+ try {
477
+ const parsed = new URL(url);
478
+ if (parsed.origin !== "https://api.github.com" || parsed.username || parsed.password) return "UNKNOWN";
479
+ path = parsed.pathname;
480
+ } catch {
481
+ return "UNKNOWN";
383
482
  }
384
- const prefix = '/repos/[^/]{1,100}/[^/]{1,100}';
385
- const number = '(?:[0-9]{1,20}|\\{pull_number\\})';
386
- const routes = [
387
- ['PUT', new RegExp(`^${prefix}/pulls/${number}/merge$`, 'u'), 'pulls.merge'],
388
- ['GET', new RegExp(`^${prefix}/pulls/${number}$`, 'u'), 'pulls.get'],
389
- ['GET', new RegExp(`^${prefix}/pulls/${number}/reviews$`, 'u'), 'pulls.listReviews'],
390
- ['GET', new RegExp(`^${prefix}/pulls/${number}/reviews/(?:[0-9]{1,20}|\\{review_id\\})$`, 'u'), 'pulls.getReview'],
391
- ['GET', new RegExp(`^${prefix}/git/commits/[^/]{1,100}$`, 'u'), 'git.getCommit'],
392
- ['GET', new RegExp(`^${prefix}/git/ref/.{1,300}$`, 'u'), 'git.getRef'],
393
- ['GET', new RegExp(`^${prefix}/issues/(?:[0-9]{1,20}|\\{issue_number\\})$`, 'u'), 'issues.get'],
394
- ['PATCH', new RegExp(`^${prefix}/issues/(?:[0-9]{1,20}|\\{issue_number\\})$`, 'u'), 'issues.update'],
395
- ];
396
- return routes.find(([verb, pattern]) => verb === method && pattern.test(path))?.[2] ?? 'UNKNOWN';
483
+ }
484
+ const prefix = "/repos/[^/]{1,100}/[^/]{1,100}";
485
+ const number = "(?:[0-9]{1,20}|\\{pull_number\\})";
486
+ const routes = [
487
+ ["PUT", new RegExp(`^${prefix}/pulls/${number}/merge$`, "u"), "pulls.merge"],
488
+ ["GET", new RegExp(`^${prefix}/pulls/${number}$`, "u"), "pulls.get"],
489
+ ["GET", new RegExp(`^${prefix}/pulls/${number}/reviews$`, "u"), "pulls.listReviews"],
490
+ ["GET", new RegExp(`^${prefix}/pulls/${number}/reviews/(?:[0-9]{1,20}|\\{review_id\\})$`, "u"), "pulls.getReview"],
491
+ ["GET", new RegExp(`^${prefix}/git/commits/[^/]{1,100}$`, "u"), "git.getCommit"],
492
+ ["GET", new RegExp(`^${prefix}/git/ref/.{1,300}$`, "u"), "git.getRef"],
493
+ ["GET", new RegExp(`^${prefix}/issues/(?:[0-9]{1,20}|\\{issue_number\\})$`, "u"), "issues.get"],
494
+ ["PATCH", new RegExp(`^${prefix}/issues/(?:[0-9]{1,20}|\\{issue_number\\})$`, "u"), "issues.update"]
495
+ ];
496
+ return routes.find(([verb, pattern]) => verb === method && pattern.test(path))?.[2] ?? "UNKNOWN";
397
497
  }
398
498
  function safeMachineRequestError(error, phase, endpoint) {
399
- const status = ownData(error, 'status');
400
- const safe = new DeliveryError(status === 401
401
- ? 'Machine GitHub session is invalid or expired; verify the selected github.com account.'
402
- : status === 403 || status === 404
403
- ? 'Machine GitHub session cannot access the selected repository or operation; verify its existing permissions.'
404
- : 'Machine GitHub request failed; verify the selected account and repository access.');
405
- if (typeof status === 'number' && Number.isSafeInteger(status) && status >= 400 && status <= 599)
406
- Object.assign(safe, { status });
407
- const headers = ownData(error, 'headers') ?? ownData(ownData(error, 'response'), 'headers');
408
- setMachineRequestDiagnostics(safe, {
409
- phase,
410
- endpoint,
411
- status,
412
- code: ownData(error, 'code'),
413
- requestId: ownData(headers, 'x-github-request-id'),
414
- retryAfter: ownData(headers, 'retry-after'),
415
- resetAt: ownData(headers, 'x-ratelimit-reset'),
416
- remaining: ownData(headers, 'x-ratelimit-remaining'),
417
- });
418
- return safe;
499
+ const status = ownData(error, "status");
500
+ const safe = new DeliveryError(
501
+ status === 401 ? "Machine GitHub session is invalid or expired; verify the selected github.com account." : status === 403 || status === 404 ? "Machine GitHub session cannot access the selected repository or operation; verify its existing permissions." : "Machine GitHub request failed; verify the selected account and repository access."
502
+ );
503
+ if (typeof status === "number" && Number.isSafeInteger(status) && status >= 400 && status <= 599)
504
+ Object.assign(safe, { status });
505
+ const headers = ownData(error, "headers") ?? ownData(ownData(error, "response"), "headers");
506
+ setMachineRequestDiagnostics(safe, {
507
+ phase,
508
+ endpoint,
509
+ status,
510
+ code: ownData(error, "code"),
511
+ requestId: ownData(headers, "x-github-request-id"),
512
+ retryAfter: ownData(headers, "retry-after"),
513
+ resetAt: ownData(headers, "x-ratelimit-reset"),
514
+ remaining: ownData(headers, "x-ratelimit-remaining")
515
+ });
516
+ return safe;
419
517
  }
420
- //# sourceMappingURL=client.js.map
518
+ export {
519
+ assertDeliveryRolePermissions,
520
+ createDeliveryGitHubClients,
521
+ hasBranchProtectionAbsence,
522
+ retainMachineAuthorForConfiguration,
523
+ withAuthorGitToken
524
+ };
525
+ //# sourceMappingURL=client.js.map