@aspruyt/xfg 8.5.6 → 9.0.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 (58) hide show
  1. package/dist/cli/settings-factories.d.ts +2 -1
  2. package/dist/cli/settings-factories.js +6 -1
  3. package/dist/cli/settings-report-builder.d.ts +6 -1
  4. package/dist/cli/settings-report-builder.js +12 -0
  5. package/dist/cli/settings-runner.js +7 -0
  6. package/dist/cli/types.d.ts +4 -9
  7. package/dist/config/array-directive.d.ts +21 -0
  8. package/dist/config/array-directive.js +88 -0
  9. package/dist/config/drop-repeated-items.d.ts +2 -0
  10. package/dist/config/drop-repeated-items.js +19 -0
  11. package/dist/config/index.d.ts +2 -2
  12. package/dist/config/index.js +1 -3
  13. package/dist/config/merge.d.ts +6 -1
  14. package/dist/config/merge.js +13 -29
  15. package/dist/config/normalizer.d.ts +0 -8
  16. package/dist/config/normalizer.js +195 -238
  17. package/dist/config/types.d.ts +68 -37
  18. package/dist/config/types.js +6 -0
  19. package/dist/config/validator.d.ts +3 -9
  20. package/dist/config/validator.js +41 -45
  21. package/dist/config/validators/actions-validator.d.ts +7 -0
  22. package/dist/config/validators/actions-validator.js +139 -0
  23. package/dist/config/validators/ai-validator.d.ts +7 -1
  24. package/dist/config/validators/ai-validator.js +41 -14
  25. package/dist/config/validators/file-validator.js +2 -6
  26. package/dist/config/validators/group-validator.js +3 -10
  27. package/dist/config/validators/inherit-flag.d.ts +3 -0
  28. package/dist/config/validators/inherit-flag.js +14 -0
  29. package/dist/config/validators/pr-options-validator.d.ts +3 -0
  30. package/dist/config/validators/pr-options-validator.js +32 -0
  31. package/dist/config/validators/repo-entry-validator.js +2 -9
  32. package/dist/config/validators/ruleset-validator.d.ts +0 -3
  33. package/dist/config/validators/ruleset-validator.js +39 -58
  34. package/dist/config/validators/shared.d.ts +9 -0
  35. package/dist/config/validators/shared.js +98 -28
  36. package/dist/settings/actions/diff.d.ts +11 -0
  37. package/dist/settings/actions/diff.js +32 -0
  38. package/dist/settings/actions/endpoints.d.ts +21 -0
  39. package/dist/settings/actions/endpoints.js +89 -0
  40. package/dist/settings/actions/formatter.d.ts +10 -0
  41. package/dist/settings/actions/formatter.js +11 -0
  42. package/dist/settings/actions/github-actions-strategy.d.ts +16 -0
  43. package/dist/settings/actions/github-actions-strategy.js +23 -0
  44. package/dist/settings/actions/index.d.ts +3 -0
  45. package/dist/settings/actions/index.js +2 -0
  46. package/dist/settings/actions/processor.d.ts +19 -0
  47. package/dist/settings/actions/processor.js +88 -0
  48. package/dist/settings/actions/resolve.d.ts +15 -0
  49. package/dist/settings/actions/resolve.js +42 -0
  50. package/dist/settings/actions/types.d.ts +9 -0
  51. package/dist/settings/actions/types.js +1 -0
  52. package/dist/settings/environments/processor.js +1 -1
  53. package/dist/settings/index.d.ts +1 -0
  54. package/dist/settings/index.js +1 -0
  55. package/dist/settings/labels/diff.js +1 -2
  56. package/dist/shared/credential-env.d.ts +4 -3
  57. package/dist/shared/credential-env.js +12 -7
  58. package/package.json +4 -2
@@ -1,7 +1,10 @@
1
1
  import { isTextContent, isObjectContent, isStructuredFileExtension, validValues, VALID_STRATEGIES, } from "./file-validator.js";
2
2
  import { validateRuleset } from "./ruleset-validator.js";
3
3
  import { validateRepoSettings } from "./repo-settings-validator.js";
4
+ import { validateActionsSettings } from "./actions-validator.js";
5
+ import { assertNoRootInherit, validateInheritFlag } from "./inherit-flag.js";
4
6
  import { isPlainObject } from "../../shared/type-guards.js";
7
+ import { arrayValues, explainNotArray } from "../array-directive.js";
5
8
  import { ValidationError } from "../../shared/errors.js";
6
9
  export function buildRootSettingsContext(config) {
7
10
  return {
@@ -11,6 +14,8 @@ export function buildRootSettingsContext(config) {
11
14
  hasRepoSettings: config.settings?.repo !== undefined && config.settings.repo !== false,
12
15
  hasCodeScanningSettings: config.settings?.codeScanning !== undefined &&
13
16
  config.settings.codeScanning !== false,
17
+ hasActionsSettings: config.settings?.actions !== undefined &&
18
+ config.settings.actions !== false,
14
19
  labelNames: config.settings?.labels
15
20
  ? Object.keys(config.settings.labels).filter((k) => k !== "inherit")
16
21
  : [],
@@ -72,6 +77,15 @@ export function validateFileConfigFields(fileConfig, fileName, context) {
72
77
  }
73
78
  }
74
79
  }
80
+ /** `inherit` on a ruleset, label or environment entry; root entries have nothing to inherit. */
81
+ function validateEntryInherit(entry, kind, name, context, isRoot) {
82
+ if (!isPlainObject(entry))
83
+ return;
84
+ const entryName = `${kind} '${name}'`;
85
+ if (isRoot)
86
+ assertNoRootInherit(entry, entryName, context);
87
+ validateInheritFlag(entry, `${context}: ${entryName}`);
88
+ }
75
89
  function validateLabel(label, name, context) {
76
90
  if (!isPlainObject(label)) {
77
91
  throw new ValidationError(`${context}: label '${name}' must be an object`);
@@ -115,10 +129,9 @@ function validateCodeScanningSettings(settings, context) {
115
129
  if (!isPlainObject(settings)) {
116
130
  throw new ValidationError(`${context}: must be an object`);
117
131
  }
118
- if (settings.state === undefined) {
119
- throw new ValidationError(`${context}: state is required`);
120
- }
121
- if (!VALID_CODE_SCANNING_STATES.includes(settings.state)) {
132
+ validateInheritFlag(settings, context);
133
+ if (settings.state !== undefined &&
134
+ !VALID_CODE_SCANNING_STATES.includes(settings.state)) {
122
135
  throw new ValidationError(`${context}: state must be one of: ${VALID_CODE_SCANNING_STATES.join(", ")}`);
123
136
  }
124
137
  if (settings.querySuite !== undefined &&
@@ -126,16 +139,23 @@ function validateCodeScanningSettings(settings, context) {
126
139
  throw new ValidationError(`${context}: querySuite must be one of: ${VALID_CODE_SCANNING_QUERY_SUITES.join(", ")}`);
127
140
  }
128
141
  if (settings.languages !== undefined) {
129
- if (!Array.isArray(settings.languages)) {
130
- throw new ValidationError(`${context}: languages must be an array`);
142
+ const languages = arrayValues(settings.languages);
143
+ if (languages === null) {
144
+ throw new ValidationError(explainNotArray(`${context}: languages must be an array or $arrayMerge directive`, settings.languages));
131
145
  }
132
- for (const lang of settings.languages) {
146
+ for (const lang of languages) {
133
147
  if (!VALID_CODE_SCANNING_LANGUAGES.includes(lang)) {
134
148
  throw new ValidationError(`${context}: invalid language "${lang}". Valid languages: ${VALID_CODE_SCANNING_LANGUAGES.join(", ")}`);
135
149
  }
136
150
  }
137
151
  }
138
152
  }
153
+ /** A layer may omit `state` and inherit it, so only the merged block can be checked. */
154
+ export function validateMergedCodeScanningSettings(codeScanning, context) {
155
+ if (codeScanning && codeScanning.state === undefined) {
156
+ throw new ValidationError(`${context} codeScanning: state is required, but no layer sets it (a layer with inherit: false drops the inherited state)`);
157
+ }
158
+ }
139
159
  function validateSettingsRulesets(settings, context, rootCtx) {
140
160
  if (settings.rulesets === undefined)
141
161
  return;
@@ -152,6 +172,7 @@ function validateSettingsRulesets(settings, context, rootCtx) {
152
172
  }
153
173
  continue;
154
174
  }
175
+ validateEntryInherit(ruleset, "ruleset", name, context, !rootCtx);
155
176
  validateRuleset(ruleset, name, context);
156
177
  }
157
178
  }
@@ -171,6 +192,7 @@ function validateSettingsLabels(settings, context, rootCtx) {
171
192
  }
172
193
  continue;
173
194
  }
195
+ validateEntryInherit(label, "label", name, context, !rootCtx);
174
196
  validateLabel(label, name, context);
175
197
  }
176
198
  }
@@ -193,6 +215,7 @@ function validateSettingsRepo(settings, context, rootCtx) {
193
215
  return;
194
216
  }
195
217
  validateRepoSettings(settings.repo, context);
218
+ validateInheritFlag(settings.repo, `${context} repo`);
196
219
  }
197
220
  function validateSettingsCodeScanning(settings, context, rootCtx) {
198
221
  if (settings.codeScanning === undefined)
@@ -208,6 +231,20 @@ function validateSettingsCodeScanning(settings, context, rootCtx) {
208
231
  }
209
232
  validateCodeScanningSettings(settings.codeScanning, `${context} codeScanning`);
210
233
  }
234
+ function validateSettingsActions(settings, context, rootCtx) {
235
+ if (settings.actions === undefined)
236
+ return;
237
+ if (settings.actions === false) {
238
+ if (!rootCtx) {
239
+ throw new ValidationError(`${context}: actions: false is not valid at root level. Define actions settings or remove the field.`);
240
+ }
241
+ if (!rootCtx.hasActionsSettings) {
242
+ throw new ValidationError(`${context}: Cannot opt out of actions settings — not defined in root settings.actions`);
243
+ }
244
+ return;
245
+ }
246
+ validateActionsSettings(settings.actions, `${context} actions`);
247
+ }
211
248
  function validateSettingsSecrets(settings, context) {
212
249
  if (settings.secrets === undefined)
213
250
  return;
@@ -248,11 +285,11 @@ function validateSettingsCollaborators(settings, context) {
248
285
  throw new ValidationError(`${context}: collaborators.${key} must be a boolean`);
249
286
  }
250
287
  }
251
- const users = collaborators.users;
252
- if (users === undefined)
288
+ if (collaborators.users === undefined)
253
289
  return;
254
- if (!Array.isArray(users)) {
255
- throw new ValidationError(`${context}: collaborators.users must be an array of GitHub usernames`);
290
+ const users = arrayValues(collaborators.users);
291
+ if (users === null) {
292
+ throw new ValidationError(explainNotArray(`${context}: collaborators.users must be an array of GitHub usernames or $arrayMerge directive`, collaborators.users));
256
293
  }
257
294
  for (const user of users) {
258
295
  if (typeof user !== "string" || !GITHUB_USERNAME_PATTERN.test(user)) {
@@ -260,11 +297,16 @@ function validateSettingsCollaborators(settings, context) {
260
297
  }
261
298
  }
262
299
  }
263
- const ENVIRONMENT_KEYS = new Set(["deploymentBranchPolicy", "secrets"]);
300
+ const ENVIRONMENT_KEYS = new Set([
301
+ "deploymentBranchPolicy",
302
+ "secrets",
303
+ "inherit",
304
+ ]);
264
305
  const BRANCH_POLICY_KEYS = new Set([
265
306
  "protectedBranches",
266
307
  "custom",
267
308
  "deleteOrphaned",
309
+ "inherit",
268
310
  ]);
269
311
  const BRANCH_PATTERN_KEYS = new Set(["type", "name"]);
270
312
  const ENVIRONMENT_NAME_MAX_LENGTH = 255;
@@ -276,11 +318,15 @@ function assertKnownKeys(obj, allowed, context) {
276
318
  }
277
319
  }
278
320
  function validateBranchPatterns(custom, context) {
279
- if (!Array.isArray(custom) || custom.length === 0) {
280
- throw new ValidationError(`${context}: custom must be a non-empty array`);
321
+ if (isPlainObject(custom) && custom.$arrayMerge === "merge") {
322
+ throw new ValidationError(`${context}: custom does not accept $arrayMerge: merge, because a pattern is identified by type and name together. Use append, prepend or replace.`);
323
+ }
324
+ const patterns = arrayValues(custom);
325
+ if (patterns === null || patterns.length === 0) {
326
+ throw new ValidationError(`${context}: custom must be a non-empty array or $arrayMerge directive`);
281
327
  }
282
328
  const seen = new Set();
283
- custom.forEach((pattern, i) => {
329
+ patterns.forEach((pattern, i) => {
284
330
  const ctx = `${context}: custom[${i}]`;
285
331
  if (!isPlainObject(pattern)) {
286
332
  throw new ValidationError(`${ctx} must be an object`);
@@ -299,7 +345,7 @@ function validateBranchPatterns(custom, context) {
299
345
  seen.add(key);
300
346
  });
301
347
  }
302
- function validateDeploymentBranchPolicy(policy, context, isRoot) {
348
+ function validateDeploymentBranchPolicyLayer(policy, context, isRoot) {
303
349
  const ctx = `${context} deploymentBranchPolicy`;
304
350
  if (policy === false) {
305
351
  if (isRoot) {
@@ -311,24 +357,43 @@ function validateDeploymentBranchPolicy(policy, context, isRoot) {
311
357
  throw new ValidationError(`${ctx} must be an object`);
312
358
  }
313
359
  assertKnownKeys(policy, BRANCH_POLICY_KEYS, `${context}: deploymentBranchPolicy`);
360
+ if (isRoot)
361
+ assertNoRootInherit(policy, "deploymentBranchPolicy", context);
362
+ validateInheritFlag(policy, `${context}: deploymentBranchPolicy`);
363
+ if (policy.protectedBranches !== undefined &&
364
+ policy.protectedBranches !== true) {
365
+ throw new ValidationError(`${ctx}: protectedBranches must be true. Omit deploymentBranchPolicy to let any branch deploy.`);
366
+ }
367
+ if (policy.protectedBranches !== undefined && policy.custom !== undefined) {
368
+ throw new ValidationError(`${ctx} has both 'protectedBranches: true' and 'custom'. Set only one.`);
369
+ }
370
+ if (policy.custom !== undefined) {
371
+ validateBranchPatterns(policy.custom, ctx);
372
+ }
373
+ if (policy.deleteOrphaned !== undefined &&
374
+ typeof policy.deleteOrphaned !== "boolean") {
375
+ throw new ValidationError(`${context}: deploymentBranchPolicy: deleteOrphaned must be a boolean`);
376
+ }
377
+ }
378
+ /**
379
+ * A layer sets only some fields, so the options that must go together are
380
+ * checked on the merged policy.
381
+ */
382
+ export function validateDeploymentBranchPolicy(policy, context) {
383
+ const ctx = `${context} deploymentBranchPolicy`;
314
384
  const hasProtected = policy.protectedBranches !== undefined;
315
385
  const hasCustom = policy.custom !== undefined;
316
- if (hasProtected === hasCustom) {
317
- throw new ValidationError(`${ctx} needs exactly one of 'protectedBranches: true' or 'custom'`);
386
+ if (hasProtected && hasCustom) {
387
+ throw new ValidationError(`${ctx} has both 'protectedBranches: true' and 'custom'. Set inherit: false on the layer that changes the policy kind to drop the inherited one.`);
318
388
  }
319
- if (hasProtected && policy.protectedBranches !== true) {
320
- throw new ValidationError(`${ctx}: protectedBranches must be true. Omit deploymentBranchPolicy to let any branch deploy.`);
389
+ if (!hasProtected && !hasCustom) {
390
+ throw new ValidationError(`${ctx} needs exactly one of 'protectedBranches: true' or 'custom'`);
321
391
  }
322
392
  if (hasCustom) {
323
393
  validateBranchPatterns(policy.custom, ctx);
324
394
  }
325
- if (policy.deleteOrphaned !== undefined) {
326
- if (typeof policy.deleteOrphaned !== "boolean") {
327
- throw new ValidationError(`${context}: deploymentBranchPolicy: deleteOrphaned must be a boolean`);
328
- }
329
- if (!hasCustom) {
330
- throw new ValidationError(`${context}: deploymentBranchPolicy: deleteOrphaned only applies to a 'custom' policy`);
331
- }
395
+ if (policy.deleteOrphaned !== undefined && !hasCustom) {
396
+ throw new ValidationError(`${context}: deploymentBranchPolicy: deleteOrphaned only applies to a 'custom' policy`);
332
397
  }
333
398
  }
334
399
  function validateEnvironmentSecrets(secrets, context) {
@@ -366,6 +431,7 @@ function validateSettingsEnvironments(settings, context, rootCtx) {
366
431
  }
367
432
  validateEnvironmentName(name, context, seenNames);
368
433
  if (env !== false) {
434
+ validateEntryInherit(env, "environment", name, context, !rootCtx);
369
435
  validateEnvironmentEntry(env, `${context}: environment '${name}'`, !rootCtx);
370
436
  }
371
437
  }
@@ -394,7 +460,7 @@ function validateEnvironmentEntry(env, envCtx, isRoot) {
394
460
  }
395
461
  assertKnownKeys(env, ENVIRONMENT_KEYS, envCtx);
396
462
  if (env.deploymentBranchPolicy !== undefined) {
397
- validateDeploymentBranchPolicy(env.deploymentBranchPolicy, envCtx, isRoot);
463
+ validateDeploymentBranchPolicyLayer(env.deploymentBranchPolicy, envCtx, isRoot);
398
464
  }
399
465
  if (env.secrets !== undefined) {
400
466
  validateEnvironmentSecrets(env.secrets, envCtx);
@@ -409,6 +475,7 @@ export function validateSettings(settings, context, rootCtx) {
409
475
  validateSettingsDeleteOrphaned(settings, context);
410
476
  validateSettingsRepo(settings, context, rootCtx);
411
477
  validateSettingsCodeScanning(settings, context, rootCtx);
478
+ validateSettingsActions(settings, context, rootCtx);
412
479
  validateSettingsSecrets(settings, context);
413
480
  validateSettingsCollaborators(settings, context);
414
481
  validateSettingsEnvironments(settings, context, rootCtx);
@@ -434,4 +501,7 @@ export function enrichSettingsContext(rootCtx, settings) {
434
501
  if (settings.codeScanning !== undefined && settings.codeScanning !== false) {
435
502
  rootCtx.hasCodeScanningSettings = true;
436
503
  }
504
+ if (settings.actions !== undefined && settings.actions !== false) {
505
+ rootCtx.hasActionsSettings = true;
506
+ }
437
507
  }
@@ -0,0 +1,11 @@
1
+ import type { ActionsSettings } from "../../config/index.js";
2
+ import type { SettingsAction } from "../base-processor.js";
3
+ export interface ActionsChange {
4
+ property: keyof ActionsSettings;
5
+ action: SettingsAction;
6
+ oldValue?: unknown;
7
+ newValue?: unknown;
8
+ }
9
+ /** Only fields set in desired are compared; patternsAllowed compares as a set. */
10
+ export declare function diffActions(current: ActionsSettings, desired: ActionsSettings): ActionsChange[];
11
+ export declare function hasActionsChanges(changes: ActionsChange[]): boolean;
@@ -0,0 +1,32 @@
1
+ import { ACTIONS_ENDPOINTS } from "./endpoints.js";
2
+ const FIELD_ORDER = ACTIONS_ENDPOINTS.flatMap((e) => e.fields.map((f) => f.setting));
3
+ function sameValue(current, desired) {
4
+ if (Array.isArray(current) && Array.isArray(desired)) {
5
+ const currentSet = new Set(current);
6
+ const desiredSet = new Set(desired);
7
+ return (currentSet.size === desiredSet.size &&
8
+ [...desiredSet].every((v) => currentSet.has(v)));
9
+ }
10
+ return current === desired;
11
+ }
12
+ function classify(oldValue, newValue) {
13
+ if (sameValue(oldValue, newValue))
14
+ return "unchanged";
15
+ return oldValue === undefined ? "create" : "update";
16
+ }
17
+ /** Only fields set in desired are compared; patternsAllowed compares as a set. */
18
+ export function diffActions(current, desired) {
19
+ const changes = [];
20
+ for (const property of FIELD_ORDER) {
21
+ const newValue = desired[property];
22
+ if (newValue === undefined)
23
+ continue;
24
+ const oldValue = current[property];
25
+ const action = classify(oldValue, newValue);
26
+ changes.push({ property, action, oldValue, newValue });
27
+ }
28
+ return changes;
29
+ }
30
+ export function hasActionsChanges(changes) {
31
+ return changes.some((c) => c.action !== "unchanged");
32
+ }
@@ -0,0 +1,21 @@
1
+ import type { ActionsSettings } from "../../config/index.js";
2
+ import type { ActionsApiBody, ActionsEndpointName } from "./types.js";
3
+ interface ActionsEndpointField {
4
+ setting: keyof ActionsSettings;
5
+ api: string;
6
+ }
7
+ export interface ActionsEndpoint {
8
+ name: ActionsEndpointName;
9
+ /** Path under /repos/{owner}/{repo}/actions/ */
10
+ path: string;
11
+ fields: readonly ActionsEndpointField[];
12
+ }
13
+ export declare const ACTIONS_ENDPOINTS: readonly ActionsEndpoint[];
14
+ export declare function endpointByName(name: ActionsEndpointName): ActionsEndpoint;
15
+ export declare function readEndpoint(endpoint: ActionsEndpoint, body: ActionsApiBody): ActionsSettings;
16
+ /**
17
+ * GitHub doesn't document whether a PUT keeps omitted fields, so the current
18
+ * value of every unconfigured field is sent too.
19
+ */
20
+ export declare function buildPayload(endpoint: ActionsEndpoint, desired: ActionsSettings, current: ActionsSettings): ActionsApiBody;
21
+ export {};
@@ -0,0 +1,89 @@
1
+ // Order is the write order: selected-actions needs allowed_actions: selected set first.
2
+ export const ACTIONS_ENDPOINTS = [
3
+ {
4
+ name: "permissions",
5
+ path: "permissions",
6
+ fields: [
7
+ { setting: "enabled", api: "enabled" },
8
+ { setting: "allowedActions", api: "allowed_actions" },
9
+ { setting: "shaPinningRequired", api: "sha_pinning_required" },
10
+ ],
11
+ },
12
+ {
13
+ name: "selectedActions",
14
+ path: "permissions/selected-actions",
15
+ fields: [
16
+ { setting: "githubOwnedAllowed", api: "github_owned_allowed" },
17
+ { setting: "verifiedAllowed", api: "verified_allowed" },
18
+ { setting: "patternsAllowed", api: "patterns_allowed" },
19
+ ],
20
+ },
21
+ {
22
+ name: "workflow",
23
+ path: "permissions/workflow",
24
+ fields: [
25
+ {
26
+ setting: "defaultWorkflowPermissions",
27
+ api: "default_workflow_permissions",
28
+ },
29
+ {
30
+ setting: "canApprovePullRequestReviews",
31
+ api: "can_approve_pull_request_reviews",
32
+ },
33
+ ],
34
+ },
35
+ {
36
+ name: "forkPrApproval",
37
+ path: "permissions/fork-pr-contributor-approval",
38
+ fields: [{ setting: "forkPrApprovalPolicy", api: "approval_policy" }],
39
+ },
40
+ {
41
+ name: "artifactRetention",
42
+ path: "permissions/artifact-and-log-retention",
43
+ fields: [{ setting: "artifactAndLogRetentionDays", api: "days" }],
44
+ },
45
+ {
46
+ name: "cacheRetention",
47
+ path: "cache/retention-limit",
48
+ fields: [
49
+ { setting: "cacheRetentionDays", api: "max_cache_retention_days" },
50
+ ],
51
+ },
52
+ {
53
+ name: "cacheStorage",
54
+ path: "cache/storage-limit",
55
+ fields: [{ setting: "cacheSizeGb", api: "max_cache_size_gb" }],
56
+ },
57
+ ];
58
+ export function endpointByName(name) {
59
+ const endpoint = ACTIONS_ENDPOINTS.find((e) => e.name === name);
60
+ if (!endpoint)
61
+ throw new Error(`Unknown Actions endpoint: ${name}`);
62
+ return endpoint;
63
+ }
64
+ export function readEndpoint(endpoint, body) {
65
+ const result = {};
66
+ for (const { setting, api } of endpoint.fields) {
67
+ if (body[api] !== undefined)
68
+ result[setting] = body[api];
69
+ }
70
+ return result;
71
+ }
72
+ /**
73
+ * GitHub doesn't document whether a PUT keeps omitted fields, so the current
74
+ * value of every unconfigured field is sent too.
75
+ */
76
+ export function buildPayload(endpoint, desired, current) {
77
+ // Only enabled is written while Actions is off: GitHub answers 409 to allowed_actions with enabled: false
78
+ if (endpoint.name === "permissions" &&
79
+ (desired.enabled ?? current.enabled) === false) {
80
+ return { enabled: false };
81
+ }
82
+ const body = {};
83
+ for (const { setting, api } of endpoint.fields) {
84
+ const value = desired[setting] ?? current[setting];
85
+ if (value !== undefined)
86
+ body[api] = value;
87
+ }
88
+ return body;
89
+ }
@@ -0,0 +1,10 @@
1
+ import type { ActionsChange } from "./diff.js";
2
+ import { type PlanEntry } from "../base-processor.js";
3
+ export type ActionsPlanEntry = PlanEntry;
4
+ export interface ActionsPlanResult {
5
+ lines: string[];
6
+ creates: number;
7
+ updates: number;
8
+ entries: ActionsPlanEntry[];
9
+ }
10
+ export declare function formatActionsPlan(changes: ActionsChange[]): ActionsPlanResult;
@@ -0,0 +1,11 @@
1
+ import { formatScalarValue } from "../../shared/string-utils.js";
2
+ import { formatChangeLines } from "../base-processor.js";
3
+ function formatValue(val) {
4
+ if (Array.isArray(val)) {
5
+ return `[${val.join(", ")}]`;
6
+ }
7
+ return formatScalarValue(val) ?? String(val);
8
+ }
9
+ export function formatActionsPlan(changes) {
10
+ return formatChangeLines(changes, formatValue);
11
+ }
@@ -0,0 +1,16 @@
1
+ import type { ICommandExecutor } from "../../shared/command-executor.js";
2
+ import { type RepoInfo } from "../../repo/index.js";
3
+ import { type GhApiOptions } from "../../shared/gh-api-utils.js";
4
+ import type { ActionsApiBody, ActionsEndpointName, IActionsStrategy } from "./types.js";
5
+ interface GitHubActionsStrategyOptions {
6
+ retries?: number;
7
+ cwd: string;
8
+ }
9
+ export declare class GitHubActionsStrategy implements IActionsStrategy {
10
+ private readonly api;
11
+ constructor(executor: ICommandExecutor, options: GitHubActionsStrategyOptions);
12
+ get(repoInfo: RepoInfo, endpoint: ActionsEndpointName, options?: GhApiOptions): Promise<ActionsApiBody>;
13
+ update(repoInfo: RepoInfo, endpoint: ActionsEndpointName, payload: ActionsApiBody, options?: GhApiOptions): Promise<void>;
14
+ private url;
15
+ }
16
+ export {};
@@ -0,0 +1,23 @@
1
+ import { assertGitHubRepo } from "../../repo/index.js";
2
+ import { GhApiClient } from "../../shared/gh-api-utils.js";
3
+ import { parseApiJson } from "../../shared/json-utils.js";
4
+ import { endpointByName } from "./endpoints.js";
5
+ export class GitHubActionsStrategy {
6
+ api;
7
+ constructor(executor, options) {
8
+ this.api = new GhApiClient(executor, options.retries ?? 3, options.cwd);
9
+ }
10
+ async get(repoInfo, endpoint, options) {
11
+ const url = this.url(repoInfo, endpoint);
12
+ const result = await this.api.call("GET", url, { options });
13
+ return parseApiJson(result, `Actions ${endpoint} settings response`);
14
+ }
15
+ async update(repoInfo, endpoint, payload, options) {
16
+ const url = this.url(repoInfo, endpoint);
17
+ await this.api.call("PUT", url, { payload, options });
18
+ }
19
+ url(repoInfo, endpoint) {
20
+ assertGitHubRepo(repoInfo, "GitHub Actions strategy");
21
+ return `/repos/${repoInfo.owner}/${repoInfo.repo}/actions/${endpointByName(endpoint).path}`;
22
+ }
23
+ }
@@ -0,0 +1,3 @@
1
+ export { type ActionsPlanEntry } from "./formatter.js";
2
+ export { ActionsProcessor, type IActionsProcessor } from "./processor.js";
3
+ export { GitHubActionsStrategy } from "./github-actions-strategy.js";
@@ -0,0 +1,2 @@
1
+ export { ActionsProcessor } from "./processor.js";
2
+ export { GitHubActionsStrategy } from "./github-actions-strategy.js";
@@ -0,0 +1,19 @@
1
+ import type { RepoConfig } from "../../config/index.js";
2
+ import type { RepoInfo } from "../../repo/index.js";
3
+ import type { IActionsStrategy } from "./types.js";
4
+ import { type ActionsPlanResult } from "./formatter.js";
5
+ import { type BaseProcessorOptions, type BaseProcessorResult, type ISettingsProcessor, type ChangeCounts } from "../base-processor.js";
6
+ export type IActionsProcessor = ISettingsProcessor<ActionsProcessorOptions, ActionsProcessorResult>;
7
+ export type ActionsProcessorOptions = BaseProcessorOptions;
8
+ export interface ActionsProcessorResult extends BaseProcessorResult {
9
+ changes?: ChangeCounts;
10
+ planOutput?: ActionsPlanResult;
11
+ warnings?: string[];
12
+ }
13
+ export declare class ActionsProcessor implements IActionsProcessor {
14
+ private readonly strategy;
15
+ constructor(strategy: IActionsStrategy);
16
+ process(repoConfig: RepoConfig, repoInfo: RepoInfo, options: ActionsProcessorOptions): Promise<ActionsProcessorResult>;
17
+ private applySettings;
18
+ private readCurrent;
19
+ }
@@ -0,0 +1,88 @@
1
+ import { runSequentially } from "../../shared/sequential.js";
2
+ import { ACTIONS_ENDPOINTS, buildPayload, readEndpoint, } from "./endpoints.js";
3
+ import { resolveActionsSettings, resolveForCurrentState } from "./resolve.js";
4
+ import { diffActions, hasActionsChanges } from "./diff.js";
5
+ import { formatActionsPlan } from "./formatter.js";
6
+ import { withGitHubGuards, countActions, buildDryRunResult, buildApplyResult, } from "../base-processor.js";
7
+ function withWarnings(result, warnings) {
8
+ return warnings.length > 0 ? { ...result, warnings } : result;
9
+ }
10
+ function touches(endpoint, settings) {
11
+ return endpoint.fields.some(({ setting }) => settings[setting] !== undefined);
12
+ }
13
+ function changed(endpoint, changes) {
14
+ return changes.some((c) => c.action !== "unchanged" &&
15
+ endpoint.fields.some(({ setting }) => setting === c.property));
16
+ }
17
+ export class ActionsProcessor {
18
+ strategy;
19
+ constructor(strategy) {
20
+ this.strategy = strategy;
21
+ }
22
+ async process(repoConfig, repoInfo, options) {
23
+ return withGitHubGuards(repoConfig, repoInfo, options, {
24
+ hasDesiredSettings: (rc) => {
25
+ const actions = rc.settings?.actions;
26
+ return !!actions && Object.keys(actions).length > 0;
27
+ },
28
+ emptySettingsMessage: "No Actions settings configured",
29
+ applySettings: (githubRepo, rc, opts, token, repoName) => this.applySettings(githubRepo, rc, opts, token, repoName),
30
+ });
31
+ }
32
+ async applySettings(githubRepo, repoConfig, options, effectiveToken, repoName) {
33
+ const configured = repoConfig.settings?.actions;
34
+ if (!configured) {
35
+ throw new Error("applySettings called without actions settings");
36
+ }
37
+ const resolved = resolveActionsSettings(configured);
38
+ const strategyOptions = {
39
+ token: effectiveToken,
40
+ host: githubRepo.host,
41
+ };
42
+ const current = await this.readCurrent(githubRepo, resolved.settings, strategyOptions);
43
+ const settled = resolveForCurrentState(resolved.settings, current);
44
+ const desired = settled.settings;
45
+ const warnings = [...resolved.warnings, ...settled.warnings].map((w) => `${repoName}: ${w}`);
46
+ const endpoints = ACTIONS_ENDPOINTS.filter((e) => touches(e, desired));
47
+ if (endpoints.length === 0) {
48
+ return withWarnings({
49
+ success: true,
50
+ repoName,
51
+ message: "No Actions settings to apply",
52
+ skipped: true,
53
+ }, warnings);
54
+ }
55
+ const changes = diffActions(current, desired);
56
+ const changeCounts = countActions(changes);
57
+ if (!hasActionsChanges(changes)) {
58
+ return withWarnings({
59
+ success: true,
60
+ repoName,
61
+ message: "No changes needed",
62
+ changes: changeCounts,
63
+ }, warnings);
64
+ }
65
+ const planOutput = formatActionsPlan(changes);
66
+ if (options.dryRun) {
67
+ return withWarnings(buildDryRunResult(repoName, changeCounts, { planOutput }), warnings);
68
+ }
69
+ // Serial: GitHub asks for serial requests to avoid secondary rate limits
70
+ await runSequentially(endpoints.filter((e) => changed(e, changes)), (endpoint) => this.strategy.update(githubRepo, endpoint.name, buildPayload(endpoint, desired, current), strategyOptions));
71
+ const appliedCount = changes.filter((c) => c.action !== "unchanged").length;
72
+ return withWarnings(buildApplyResult(repoName, changeCounts, appliedCount, { planOutput }), warnings);
73
+ }
74
+ async readCurrent(githubRepo, desired, strategyOptions) {
75
+ let current = {};
76
+ // Serial: GitHub asks for serial requests to avoid secondary rate limits
77
+ await runSequentially(ACTIONS_ENDPOINTS.filter((e) => touches(e, desired)), async (endpoint) => {
78
+ // GitHub answers 409 to a selected-actions GET in any other mode
79
+ if (endpoint.name === "selectedActions" &&
80
+ current.allowedActions !== "selected") {
81
+ return;
82
+ }
83
+ const body = await this.strategy.get(githubRepo, endpoint.name, strategyOptions);
84
+ current = { ...current, ...readEndpoint(endpoint, body) };
85
+ });
86
+ return current;
87
+ }
88
+ }
@@ -0,0 +1,15 @@
1
+ import { type ActionsSettings } from "../../config/index.js";
2
+ export interface ResolvedActionsSettings {
3
+ settings: ActionsSettings;
4
+ warnings: string[];
5
+ }
6
+ /**
7
+ * Drops merged fields GitHub would reject: a repo can override an inherited
8
+ * `selected` mode or disable Actions without restating the rest of the block.
9
+ */
10
+ export declare function resolveActionsSettings(actions: ActionsSettings): ResolvedActionsSettings;
11
+ /**
12
+ * Drops the fields GitHub rejects while Actions is off on the repo, unless the
13
+ * config turns it on, so an inherited block can't fail every run.
14
+ */
15
+ export declare function resolveForCurrentState(desired: ActionsSettings, current: ActionsSettings): ResolvedActionsSettings;