@aspruyt/xfg 7.5.2 → 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/ai/client-factory.js +15 -3
  2. package/dist/cli/repo-sync-runner.d.ts +2 -0
  3. package/dist/cli/repo-sync-runner.js +18 -9
  4. package/dist/cli/secrets-command.js +16 -4
  5. package/dist/cli/settings-factories.d.ts +2 -1
  6. package/dist/cli/settings-factories.js +7 -1
  7. package/dist/cli/settings-report-builder.d.ts +6 -1
  8. package/dist/cli/settings-report-builder.js +7 -1
  9. package/dist/cli/settings-runner.js +24 -15
  10. package/dist/cli/sync-command.js +5 -1
  11. package/dist/cli/types.d.ts +4 -2
  12. package/dist/config/env.js +8 -0
  13. package/dist/config/file-reference-resolver.js +16 -13
  14. package/dist/config/index.d.ts +1 -1
  15. package/dist/config/merge.d.ts +9 -5
  16. package/dist/config/merge.js +148 -67
  17. package/dist/config/normalizer.js +87 -18
  18. package/dist/config/types.d.ts +28 -0
  19. package/dist/config/validator.js +25 -3
  20. package/dist/config/validators/ai-validator.js +2 -0
  21. package/dist/config/validators/file-validator.js +4 -1
  22. package/dist/config/validators/group-validator.js +3 -0
  23. package/dist/config/validators/ruleset-validator.js +6 -5
  24. package/dist/config/validators/shared.js +123 -0
  25. package/dist/output/settings-report.d.ts +6 -1
  26. package/dist/output/settings-report.js +31 -9
  27. package/dist/repo/detector.js +15 -24
  28. package/dist/settings/environments/diff.d.ts +22 -0
  29. package/dist/settings/environments/diff.js +78 -0
  30. package/dist/settings/environments/formatter.d.ts +17 -0
  31. package/dist/settings/environments/formatter.js +62 -0
  32. package/dist/settings/environments/github-environments-strategy.d.ts +23 -0
  33. package/dist/settings/environments/github-environments-strategy.js +54 -0
  34. package/dist/settings/environments/index.d.ts +5 -0
  35. package/dist/settings/environments/index.js +3 -0
  36. package/dist/settings/environments/processor.d.ts +21 -0
  37. package/dist/settings/environments/processor.js +100 -0
  38. package/dist/settings/environments/types.d.ts +38 -0
  39. package/dist/settings/environments/types.js +1 -0
  40. package/dist/settings/index.d.ts +1 -0
  41. package/dist/settings/index.js +1 -0
  42. package/dist/settings/secrets/diff.d.ts +2 -0
  43. package/dist/settings/secrets/formatter.d.ts +4 -0
  44. package/dist/settings/secrets/formatter.js +17 -4
  45. package/dist/settings/secrets/index.d.ts +2 -2
  46. package/dist/settings/secrets/index.js +1 -1
  47. package/dist/settings/secrets/processor.d.ts +16 -2
  48. package/dist/settings/secrets/processor.js +132 -28
  49. package/dist/shared/credential-env.d.ts +10 -0
  50. package/dist/shared/credential-env.js +50 -0
  51. package/dist/shared/gh-token-utils.d.ts +7 -1
  52. package/dist/shared/gh-token-utils.js +14 -1
  53. package/dist/shared/github-host-policy.d.ts +22 -0
  54. package/dist/shared/github-host-policy.js +61 -0
  55. package/dist/shared/path-safety.d.ts +12 -0
  56. package/dist/shared/path-safety.js +51 -0
  57. package/dist/shared/retry-utils.js +9 -13
  58. package/dist/shared/sequential.d.ts +2 -0
  59. package/dist/shared/sequential.js +4 -0
  60. package/dist/sync/auth-options-builder.d.ts +3 -1
  61. package/dist/sync/auth-options-builder.js +4 -1
  62. package/dist/sync/manifest.js +7 -2
  63. package/dist/sync/render-writer.js +7 -1
  64. package/dist/sync/repository-processor.d.ts +2 -0
  65. package/dist/sync/repository-processor.js +1 -1
  66. package/dist/vcs/ado-pr-strategy.js +3 -2
  67. package/dist/vcs/commit-strategy-selector.d.ts +3 -2
  68. package/dist/vcs/commit-strategy-selector.js +5 -4
  69. package/dist/vcs/git-ops.d.ts +3 -3
  70. package/dist/vcs/git-ops.js +29 -8
  71. package/dist/vcs/github-app-token-manager.d.ts +4 -1
  72. package/dist/vcs/github-app-token-manager.js +24 -4
  73. package/dist/vcs/github-pr-strategy.js +3 -2
  74. package/package.json +3 -2
@@ -2,6 +2,7 @@ import { extname, isAbsolute } from "node:path";
2
2
  import { isTextContent } from "../merge.js";
3
3
  import { ValidationError } from "../../shared/errors.js";
4
4
  import { isPlainObject } from "../../shared/type-guards.js";
5
+ import { hasGitDirSegment } from "../../shared/path-safety.js";
5
6
  export { isTextContent };
6
7
  export { isPlainObject as isObjectContent };
7
8
  export function validValues(values) {
@@ -27,7 +28,6 @@ export function validateFileName(fileName) {
27
28
  if (!fileName || typeof fileName !== "string") {
28
29
  throw new ValidationError("File name must be a non-empty string");
29
30
  }
30
- // Validate fileName doesn't allow path traversal
31
31
  if (fileName.includes("..") || isAbsolute(fileName)) {
32
32
  throw new ValidationError(`Invalid fileName '${fileName}': must be a relative path without '..' components`);
33
33
  }
@@ -35,5 +35,8 @@ export function validateFileName(fileName) {
35
35
  if (/[\n\r\0]/.test(fileName)) {
36
36
  throw new ValidationError(`Invalid fileName '${fileName}': cannot contain newlines or null bytes`);
37
37
  }
38
+ if (hasGitDirSegment(fileName)) {
39
+ throw new ValidationError(`Invalid fileName '${fileName}': cannot write inside a '.git' directory`);
40
+ }
38
41
  }
39
42
  export { VALID_STRATEGIES };
@@ -3,6 +3,7 @@ import { isPlainObject } from "../../shared/type-guards.js";
3
3
  import { ValidationError } from "../../shared/errors.js";
4
4
  import { validateBranchName } from "../../shared/branch-validation.js";
5
5
  import { validateAiOption } from "./ai-validator.js";
6
+ import { validateFileName } from "./file-validator.js";
6
7
  import { validateFileConfigFields, validateSettings, buildRootSettingsContext, } from "./shared.js";
7
8
  function validateGroupExtends(groupName, extends_, groupNames) {
8
9
  if (typeof extends_ === "string") {
@@ -94,6 +95,7 @@ export function validateGroups(config) {
94
95
  for (const [fileName, fileConfig] of Object.entries(group.files)) {
95
96
  if (fileName === "inherit")
96
97
  continue;
98
+ validateFileName(fileName);
97
99
  if (fileConfig === false)
98
100
  continue;
99
101
  if (fileConfig === undefined)
@@ -159,6 +161,7 @@ export function validateConditionalGroups(config) {
159
161
  for (const [fileName, fileConfig] of Object.entries(entry.files)) {
160
162
  if (fileName === "inherit")
161
163
  continue;
164
+ validateFileName(fileName);
162
165
  if (fileConfig === false)
163
166
  continue;
164
167
  if (fileConfig === undefined)
@@ -66,17 +66,18 @@ const VALID_RULE_TYPES = validValues([
66
66
  ]);
67
67
  // Intentionally duplicated from merge.ts — validator should not depend on merge internals
68
68
  const VALID_MERGE_STRATEGIES = ["replace", "append", "prepend", "merge"];
69
+ const DIRECTIVE_KEYS = new Set(["$arrayMerge", "$values", "$matchBy"]);
69
70
  /**
70
- * Checks if a value is an $arrayMerge directive: { $arrayMerge: strategy, $values: [...] }
71
+ * Checks if a value is an $arrayMerge directive:
72
+ * { $arrayMerge: strategy, $values: [...], $matchBy?: key }
71
73
  */
72
74
  function isArrayMergeDirective(value) {
73
75
  if (!isPlainObject(value))
74
76
  return false;
75
- const keys = Object.keys(value);
76
- return (keys.length === 2 &&
77
- keys.every((k) => k === "$arrayMerge" || k === "$values") &&
77
+ return (Object.keys(value).every((k) => DIRECTIVE_KEYS.has(k)) &&
78
78
  VALID_MERGE_STRATEGIES.includes(value.$arrayMerge) &&
79
- Array.isArray(value.$values));
79
+ Array.isArray(value.$values) &&
80
+ (value.$matchBy === undefined || typeof value.$matchBy === "string"));
80
81
  }
81
82
  /**
82
83
  * Extracts the $values array from a directive, or returns the value as-is if it's already an array.
@@ -260,6 +260,128 @@ function validateSettingsCollaborators(settings, context) {
260
260
  }
261
261
  }
262
262
  }
263
+ const ENVIRONMENT_KEYS = new Set(["deploymentBranchPolicy", "secrets"]);
264
+ const BRANCH_POLICY_KEYS = new Set(["protectedBranches", "custom"]);
265
+ const BRANCH_PATTERN_KEYS = new Set(["type", "name"]);
266
+ const ENVIRONMENT_NAME_MAX_LENGTH = 255;
267
+ function assertKnownKeys(obj, allowed, context) {
268
+ for (const key of Object.keys(obj)) {
269
+ if (!allowed.has(key)) {
270
+ throw new ValidationError(`${context}: unknown key '${key}'`);
271
+ }
272
+ }
273
+ }
274
+ function validateBranchPatterns(custom, context) {
275
+ if (!Array.isArray(custom) || custom.length === 0) {
276
+ throw new ValidationError(`${context}: custom must be a non-empty array`);
277
+ }
278
+ const seen = new Set();
279
+ custom.forEach((pattern, i) => {
280
+ const ctx = `${context}: custom[${i}]`;
281
+ if (!isPlainObject(pattern)) {
282
+ throw new ValidationError(`${ctx} must be an object`);
283
+ }
284
+ assertKnownKeys(pattern, BRANCH_PATTERN_KEYS, ctx);
285
+ if (pattern.type !== "branch" && pattern.type !== "tag") {
286
+ throw new ValidationError(`${ctx}.type must be 'branch' or 'tag'`);
287
+ }
288
+ if (typeof pattern.name !== "string" || pattern.name.trim() === "") {
289
+ throw new ValidationError(`${ctx}.name must be a non-empty string`);
290
+ }
291
+ const key = `${pattern.type}\u0000${pattern.name}`;
292
+ if (seen.has(key)) {
293
+ throw new ValidationError(`${context}: duplicate pattern ${pattern.type} '${pattern.name}'`);
294
+ }
295
+ seen.add(key);
296
+ });
297
+ }
298
+ function validateDeploymentBranchPolicy(policy, context, isRoot) {
299
+ const ctx = `${context} deploymentBranchPolicy`;
300
+ if (policy === false) {
301
+ if (isRoot) {
302
+ throw new ValidationError(`${context}: deploymentBranchPolicy: false is not valid at root level. Omit it to let any branch deploy.`);
303
+ }
304
+ return;
305
+ }
306
+ if (!isPlainObject(policy)) {
307
+ throw new ValidationError(`${ctx} must be an object`);
308
+ }
309
+ assertKnownKeys(policy, BRANCH_POLICY_KEYS, `${context}: deploymentBranchPolicy`);
310
+ const hasProtected = policy.protectedBranches !== undefined;
311
+ const hasCustom = policy.custom !== undefined;
312
+ if (hasProtected === hasCustom) {
313
+ throw new ValidationError(`${ctx} needs exactly one of 'protectedBranches: true' or 'custom'`);
314
+ }
315
+ if (hasProtected && policy.protectedBranches !== true) {
316
+ throw new ValidationError(`${ctx}: protectedBranches must be true. Omit deploymentBranchPolicy to let any branch deploy.`);
317
+ }
318
+ if (hasCustom) {
319
+ validateBranchPatterns(policy.custom, ctx);
320
+ }
321
+ }
322
+ function validateEnvironmentSecrets(secrets, context) {
323
+ if (!isPlainObject(secrets)) {
324
+ throw new ValidationError(`${context}: secrets must be an object`);
325
+ }
326
+ for (const [name, value] of Object.entries(secrets)) {
327
+ if (name === "deleteOrphaned" || name === "inherit") {
328
+ throw new ValidationError(`${context}: '${name}' is not supported in environment secrets`);
329
+ }
330
+ if (value === false)
331
+ continue;
332
+ if (!isPlainObject(value)) {
333
+ throw new ValidationError(`${context}: secret '${name}' must be an object with an 'env' field, or false to opt out`);
334
+ }
335
+ }
336
+ }
337
+ function validateSettingsEnvironments(settings, context, rootCtx) {
338
+ if (settings.environments === undefined)
339
+ return;
340
+ if (!isPlainObject(settings.environments)) {
341
+ throw new ValidationError(`${context}: environments must be an object`);
342
+ }
343
+ const seenNames = new Map();
344
+ for (const [name, env] of Object.entries(settings.environments)) {
345
+ if (name === "inherit") {
346
+ validateEnvironmentsInherit(env, context);
347
+ continue;
348
+ }
349
+ validateEnvironmentName(name, context, seenNames);
350
+ if (env !== false) {
351
+ validateEnvironmentEntry(env, `${context}: environment '${name}'`, !rootCtx);
352
+ }
353
+ }
354
+ }
355
+ function validateEnvironmentsInherit(value, context) {
356
+ if (typeof value !== "boolean") {
357
+ throw new ValidationError(`${context}: environments.inherit must be a boolean`);
358
+ }
359
+ }
360
+ function validateEnvironmentName(name, context, seenNames) {
361
+ if (name.trim() === "") {
362
+ throw new ValidationError(`${context}: environment name must not be blank`);
363
+ }
364
+ if (name.length > ENVIRONMENT_NAME_MAX_LENGTH) {
365
+ throw new ValidationError(`${context}: environment name '${name.slice(0, 40)}...' exceeds ${ENVIRONMENT_NAME_MAX_LENGTH} characters`);
366
+ }
367
+ const firstSpelling = seenNames.get(name.toLowerCase());
368
+ if (firstSpelling !== undefined) {
369
+ throw new ValidationError(`${context}: environment '${name}' duplicates '${firstSpelling}'; GitHub environment names ignore case`);
370
+ }
371
+ seenNames.set(name.toLowerCase(), name);
372
+ }
373
+ function validateEnvironmentEntry(env, envCtx, isRoot) {
374
+ if (!isPlainObject(env)) {
375
+ throw new ValidationError(`${envCtx} must be an object, or false to opt out`);
376
+ }
377
+ assertKnownKeys(env, ENVIRONMENT_KEYS, envCtx);
378
+ if (env.deploymentBranchPolicy !== undefined) {
379
+ validateDeploymentBranchPolicy(env.deploymentBranchPolicy, envCtx, isRoot);
380
+ }
381
+ if (env.secrets !== undefined) {
382
+ validateEnvironmentSecrets(env.secrets, envCtx);
383
+ }
384
+ }
263
385
  export function validateSettings(settings, context, rootCtx) {
264
386
  if (!isPlainObject(settings)) {
265
387
  throw new ValidationError(`${context}: settings must be an object`);
@@ -271,6 +393,7 @@ export function validateSettings(settings, context, rootCtx) {
271
393
  validateSettingsCodeScanning(settings, context, rootCtx);
272
394
  validateSettingsSecrets(settings, context);
273
395
  validateSettingsCollaborators(settings, context);
396
+ validateSettingsEnvironments(settings, context, rootCtx);
274
397
  }
275
398
  export function enrichSettingsContext(rootCtx, settings) {
276
399
  if (!settings)
@@ -1,4 +1,4 @@
1
- import type { PropertyDiff, ActiveAction, SecretsPlanEntry } from "../settings/index.js";
1
+ import type { PropertyDiff, ActiveAction, SecretsPlanEntry, EnvironmentsPlanEntry } from "../settings/index.js";
2
2
  import type { Ruleset, Label } from "../config/index.js";
3
3
  import type { DebugLog } from "../shared/logger.js";
4
4
  export interface SettingsReport {
@@ -33,6 +33,10 @@ export interface SettingsReport {
33
33
  update: number;
34
34
  delete: number;
35
35
  };
36
+ environments?: {
37
+ create: number;
38
+ update: number;
39
+ };
36
40
  };
37
41
  }
38
42
  export interface RepoChanges {
@@ -51,6 +55,7 @@ export interface RepoChanges {
51
55
  name: string;
52
56
  action: "create" | "delete";
53
57
  }[];
58
+ environments?: EnvironmentsPlanEntry[];
54
59
  error?: string;
55
60
  }
56
61
  export declare function hasRepoSettingsChanges(repo: RepoChanges): boolean;
@@ -1,4 +1,6 @@
1
1
  import chalk from "chalk";
2
+ import { formatSecretLabel } from "../settings/secrets/formatter.js";
3
+ import { formatPatternLabel, formatPolicyLine, } from "../settings/environments/formatter.js";
2
4
  import { STEP_SUMMARY_MAX_BYTES, writeGitHubStepSummary, } from "./github-summary.js";
3
5
  import { fitSummary, summaryHeader } from "./summary-budget.js";
4
6
  import { formatScalarValue, quoted } from "../shared/string-utils.js";
@@ -10,6 +12,7 @@ export function hasRepoSettingsChanges(repo) {
10
12
  (repo.variables ?? []).length > 0 ||
11
13
  (repo.secrets ?? []).length > 0 ||
12
14
  (repo.collaborators ?? []).length > 0 ||
15
+ (repo.environments ?? []).length > 0 ||
13
16
  !!repo.error);
14
17
  }
15
18
  function renderRulesetConfig(config, startDepth, formatLine) {
@@ -71,6 +74,11 @@ const SETTINGS_CATEGORIES = [
71
74
  plural: "collaborators",
72
75
  totals: (t) => t.collaborators,
73
76
  },
77
+ {
78
+ noun: "environment",
79
+ plural: "environments",
80
+ totals: (t) => t.environments,
81
+ },
74
82
  ];
75
83
  export function formatSettingsCountEntries(totals, dryRun) {
76
84
  return SETTINGS_CATEGORIES.flatMap(({ noun, plural, totals: pick }) => {
@@ -124,6 +132,22 @@ function formatValuePlain(val) {
124
132
  function formatRulesetConfigPlain(config) {
125
133
  return renderRulesetConfig(config, 1, (depth, text) => `+${" ".repeat(depth)}${text.substring(1)}`);
126
134
  }
135
+ const DIFF_SIGN = {
136
+ create: "+",
137
+ update: "!",
138
+ delete: "-",
139
+ };
140
+ function renderEnvironmentLines(entry) {
141
+ const sign = DIFF_SIGN[entry.action];
142
+ const lines = [`${sign} environment ${quoted(entry.name)}`];
143
+ const policy = formatPolicyLine(entry);
144
+ if (policy)
145
+ lines.push(`${sign} ${policy}`);
146
+ for (const pattern of entry.addedPatterns) {
147
+ lines.push(`+ ${formatPatternLabel(pattern)}`);
148
+ }
149
+ return lines;
150
+ }
127
151
  export function renderRepoSettingsDiffLines(repo, diffLines) {
128
152
  const startLength = diffLines.length;
129
153
  for (const setting of repo.settings) {
@@ -229,15 +253,7 @@ export function renderRepoSettingsDiffLines(repo, diffLines) {
229
253
  }
230
254
  // Names only: secret values are write-only and must never reach output.
231
255
  for (const secret of repo.secrets ?? []) {
232
- if (secret.action === "create") {
233
- diffLines.push(`+ secret ${quoted(secret.name)}`);
234
- }
235
- else if (secret.action === "update") {
236
- diffLines.push(`! secret ${quoted(secret.name)} (update, value write-only)`);
237
- }
238
- else {
239
- diffLines.push(`- secret ${quoted(secret.name)}`);
240
- }
256
+ diffLines.push(`${DIFF_SIGN[secret.action]} ${formatSecretLabel(secret)}`);
241
257
  }
242
258
  if ((repo.collaborators ?? []).length > 0 && diffLines.length > startLength) {
243
259
  diffLines.push("");
@@ -246,6 +262,12 @@ export function renderRepoSettingsDiffLines(repo, diffLines) {
246
262
  const sign = collaborator.action === "create" ? "+" : "-";
247
263
  diffLines.push(`${sign} collaborator ${quoted(collaborator.name)}`);
248
264
  }
265
+ if ((repo.environments ?? []).length > 0 && diffLines.length > startLength) {
266
+ diffLines.push("");
267
+ }
268
+ for (const environment of repo.environments ?? []) {
269
+ diffLines.push(...renderEnvironmentLines(environment));
270
+ }
249
271
  if (repo.error) {
250
272
  diffLines.push(`- Error: ${repo.error}`);
251
273
  }
@@ -87,32 +87,23 @@ export function parseGitUrl(gitUrl, context) {
87
87
  const host = extractHostFromUrl(gitUrl) ?? "github.com";
88
88
  return parseGitHubUrl(gitUrl, host);
89
89
  }
90
+ // gh reads a dotted first segment of OWNER/REPO as a host, so both are strict.
91
+ const GITHUB_OWNER = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
92
+ const GITHUB_REPO = /^[A-Za-z0-9._-]+$/;
90
93
  function parseGitHubUrl(gitUrl, host) {
91
- // Handle SSH format: git@hostname:owner/repo.git
92
94
  // Use (.+?) with end anchor to handle repo names with dots (e.g., my.repo.git)
93
- const sshMatch = gitUrl.match(/^git@[^:]+:([^/]+)\/(.+?)(?:\.git)?$/);
94
- if (sshMatch) {
95
- return {
96
- type: "github",
97
- gitUrl,
98
- owner: sshMatch[1],
99
- repo: sshMatch[2],
100
- host,
101
- };
102
- }
103
- // Handle HTTPS format: https://hostname/owner/repo.git
104
- // Use (.+?) with end anchor to handle repo names with dots
105
- const httpsMatch = gitUrl.match(/^https?:\/\/[^/]+\/([^/]+)\/(.+?)(?:\.git)?$/);
106
- if (httpsMatch) {
107
- return {
108
- type: "github",
109
- gitUrl,
110
- owner: httpsMatch[1],
111
- repo: httpsMatch[2],
112
- host,
113
- };
114
- }
115
- throw new ValidationError(`Unable to parse GitHub URL: ${gitUrl}`);
95
+ const match = gitUrl.match(/^git@[^:]+:([^/]+)\/(.+?)(?:\.git)?$/) ??
96
+ gitUrl.match(/^https?:\/\/[^/]+\/([^/]+)\/(.+?)(?:\.git)?$/);
97
+ if (!match) {
98
+ throw new ValidationError(`Unable to parse GitHub URL: ${gitUrl}`);
99
+ }
100
+ const [, owner, repo] = match;
101
+ if (!GITHUB_OWNER.test(owner) ||
102
+ !GITHUB_REPO.test(repo) ||
103
+ /^\.+$/.test(repo)) {
104
+ throw new ValidationError(`Invalid GitHub owner/repo in ${gitUrl}: expected OWNER/REPO with letters, digits, '-', '_' (and '.' in the repo name)`);
105
+ }
106
+ return { type: "github", gitUrl, owner, repo, host };
116
107
  }
117
108
  function parseAzureDevOpsUrl(gitUrl) {
118
109
  // Handle SSH format: git@ssh.dev.azure.com:v3/organization/project/repo
@@ -0,0 +1,22 @@
1
+ import type { DeploymentBranchPattern, DeploymentBranchPolicy, EnvironmentConfig } from "../../config/index.js";
2
+ import type { GitHubDeploymentBranchPolicy, GitHubEnvironment } from "./types.js";
3
+ export type BranchPolicyKind = "all" | "protected" | "custom";
4
+ export type EnvironmentAction = "create" | "update" | "unchanged";
5
+ export interface EnvironmentChange {
6
+ action: EnvironmentAction;
7
+ /** GitHub's spelling when the environment exists, else the config key */
8
+ name: string;
9
+ currentKind?: BranchPolicyKind;
10
+ desiredKind: BranchPolicyKind;
11
+ putPolicy: boolean;
12
+ missingPatterns: DeploymentBranchPattern[];
13
+ unmanagedPatterns: DeploymentBranchPattern[];
14
+ /** False when the existing patterns were not read, so missingPatterns may hold some that exist */
15
+ patternsKnown: boolean;
16
+ }
17
+ export declare function currentPolicyKind(policy: GitHubDeploymentBranchPolicy | null): BranchPolicyKind;
18
+ export declare function desiredPolicyKind(policy: DeploymentBranchPolicy | undefined): BranchPolicyKind;
19
+ export declare function toGitHubPolicy(kind: BranchPolicyKind): GitHubDeploymentBranchPolicy | null;
20
+ /** Existing environments whose patterns must be read before diffing. */
21
+ export declare function needsPatternLookup(desired: Record<string, EnvironmentConfig>, current: GitHubEnvironment[]): string[];
22
+ export declare function diffEnvironments(desired: Record<string, EnvironmentConfig>, current: GitHubEnvironment[], currentPatterns: ReadonlyMap<string, DeploymentBranchPattern[]>): EnvironmentChange[];
@@ -0,0 +1,78 @@
1
+ export function currentPolicyKind(policy) {
2
+ if (policy?.custom_branch_policies)
3
+ return "custom";
4
+ if (policy?.protected_branches)
5
+ return "protected";
6
+ return "all";
7
+ }
8
+ export function desiredPolicyKind(policy) {
9
+ if (policy?.custom)
10
+ return "custom";
11
+ if (policy?.protectedBranches)
12
+ return "protected";
13
+ return "all";
14
+ }
15
+ export function toGitHubPolicy(kind) {
16
+ if (kind === "all")
17
+ return null;
18
+ return {
19
+ protected_branches: kind === "protected",
20
+ custom_branch_policies: kind === "custom",
21
+ };
22
+ }
23
+ function indexByName(current) {
24
+ return new Map(current.map((env) => [env.name.toLowerCase(), env]));
25
+ }
26
+ /** Existing environments whose patterns must be read before diffing. */
27
+ export function needsPatternLookup(desired, current) {
28
+ const existing = indexByName(current);
29
+ const names = [];
30
+ for (const [name, config] of Object.entries(desired)) {
31
+ const env = existing.get(name.toLowerCase());
32
+ if (env &&
33
+ currentPolicyKind(env.deployment_branch_policy) === "custom" &&
34
+ desiredPolicyKind(config.deploymentBranchPolicy) === "custom") {
35
+ names.push(env.name);
36
+ }
37
+ }
38
+ return names;
39
+ }
40
+ function patternKey(p) {
41
+ return `${p.type}\u0000${p.name}`;
42
+ }
43
+ export function diffEnvironments(desired, current, currentPatterns) {
44
+ const existing = indexByName(current);
45
+ return Object.entries(desired).map(([configName, config]) => {
46
+ const desiredKind = desiredPolicyKind(config.deploymentBranchPolicy);
47
+ const wanted = config.deploymentBranchPolicy?.custom ?? [];
48
+ const env = existing.get(configName.toLowerCase());
49
+ if (!env) {
50
+ return {
51
+ action: "create",
52
+ name: configName,
53
+ desiredKind,
54
+ putPolicy: true,
55
+ missingPatterns: [...wanted],
56
+ unmanagedPatterns: [],
57
+ patternsKnown: true,
58
+ };
59
+ }
60
+ const currentKind = currentPolicyKind(env.deployment_branch_policy);
61
+ const putPolicy = currentKind !== desiredKind;
62
+ const known = currentPatterns.get(env.name.toLowerCase());
63
+ const have = new Set((known ?? []).map(patternKey));
64
+ const want = new Set(wanted.map(patternKey));
65
+ const missingPatterns = wanted.filter((p) => !have.has(patternKey(p)));
66
+ const unmanagedPatterns = (known ?? []).filter((p) => !want.has(patternKey(p)));
67
+ return {
68
+ action: putPolicy || missingPatterns.length > 0 ? "update" : "unchanged",
69
+ name: env.name,
70
+ currentKind,
71
+ desiredKind,
72
+ putPolicy,
73
+ missingPatterns,
74
+ unmanagedPatterns: desiredKind === "custom" ? unmanagedPatterns : [],
75
+ patternsKnown: desiredKind !== "custom" || known !== undefined,
76
+ };
77
+ });
78
+ }
@@ -0,0 +1,17 @@
1
+ import type { DeploymentBranchPattern } from "../../config/index.js";
2
+ import type { BranchPolicyKind, EnvironmentChange } from "./diff.js";
3
+ export interface EnvironmentsPlanEntry {
4
+ name: string;
5
+ action: "create" | "update";
6
+ /** Set on updates that change the policy kind */
7
+ currentKind?: BranchPolicyKind;
8
+ desiredKind: BranchPolicyKind;
9
+ addedPatterns: DeploymentBranchPattern[];
10
+ }
11
+ export interface EnvironmentsPlanResult {
12
+ lines: string[];
13
+ entries: EnvironmentsPlanEntry[];
14
+ }
15
+ export declare function formatPolicyLine(entry: EnvironmentsPlanEntry): string | null;
16
+ export declare function formatPatternLabel(pattern: DeploymentBranchPattern): string;
17
+ export declare function formatEnvironmentsPlan(changes: EnvironmentChange[], dryRun: boolean): EnvironmentsPlanResult;
@@ -0,0 +1,62 @@
1
+ import chalk from "chalk";
2
+ import { quoted } from "../../shared/string-utils.js";
3
+ import { countActions } from "../base-processor.js";
4
+ import { formatActionCountEntry } from "../../shared/count-format.js";
5
+ function toEntry(change) {
6
+ if (change.action === "unchanged")
7
+ return null;
8
+ const entry = {
9
+ name: change.name,
10
+ action: change.action,
11
+ desiredKind: change.desiredKind,
12
+ addedPatterns: change.missingPatterns,
13
+ };
14
+ if (change.action === "update" && change.putPolicy) {
15
+ entry.currentKind = change.currentKind;
16
+ }
17
+ return entry;
18
+ }
19
+ export function formatPolicyLine(entry) {
20
+ if (entry.action === "create") {
21
+ return `deployment branches: ${entry.desiredKind}`;
22
+ }
23
+ if (entry.currentKind !== undefined) {
24
+ return `deployment branches: ${entry.currentKind} → ${entry.desiredKind}`;
25
+ }
26
+ return null;
27
+ }
28
+ export function formatPatternLabel(pattern) {
29
+ return `${pattern.type} ${quoted(pattern.name)}`;
30
+ }
31
+ function formatEntry(entry) {
32
+ const color = entry.action === "create" ? chalk.green : chalk.yellow;
33
+ const sign = entry.action === "create" ? "+" : "~";
34
+ const lines = [color(` ${sign} environment ${quoted(entry.name)}`)];
35
+ const policy = formatPolicyLine(entry);
36
+ if (policy)
37
+ lines.push(` ${policy}`);
38
+ for (const pattern of entry.addedPatterns) {
39
+ lines.push(chalk.green(` + ${formatPatternLabel(pattern)}`));
40
+ }
41
+ return lines;
42
+ }
43
+ function actionRank(entry) {
44
+ return entry.action === "create" ? 0 : 1;
45
+ }
46
+ export function formatEnvironmentsPlan(changes, dryRun) {
47
+ const entries = changes
48
+ .map(toEntry)
49
+ .filter((e) => e !== null)
50
+ .sort((a, b) => actionRank(a) - actionRank(b));
51
+ const summary = formatActionCountEntry("environment", "environments", countActions(entries), dryRun);
52
+ if (!summary) {
53
+ return { lines: [], entries };
54
+ }
55
+ return {
56
+ lines: [
57
+ ...entries.flatMap(formatEntry),
58
+ ` ${dryRun ? "Plan" : "Applied"}: ${summary}`,
59
+ ],
60
+ entries,
61
+ };
62
+ }
@@ -0,0 +1,23 @@
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 { DeploymentBranchPattern } from "../../config/index.js";
5
+ import type { GitHubPublicKey, GitHubSecret } from "../secrets/types.js";
6
+ import type { GitHubDeploymentBranchPolicy, GitHubEnvironment, IEnvironmentSecretsStrategy, IEnvironmentsStrategy } from "./types.js";
7
+ interface GitHubEnvironmentsStrategyOptions {
8
+ retries?: number;
9
+ cwd: string;
10
+ }
11
+ export declare class GitHubEnvironmentsStrategy implements IEnvironmentsStrategy, IEnvironmentSecretsStrategy {
12
+ private readonly api;
13
+ constructor(executor: ICommandExecutor, options: GitHubEnvironmentsStrategyOptions);
14
+ private base;
15
+ list(repoInfo: RepoInfo, options?: GhApiOptions): Promise<GitHubEnvironment[]>;
16
+ createOrUpdate(repoInfo: RepoInfo, name: string, policy: GitHubDeploymentBranchPolicy | null, options?: GhApiOptions): Promise<void>;
17
+ listBranchPolicies(repoInfo: RepoInfo, environment: string, options?: GhApiOptions): Promise<DeploymentBranchPattern[]>;
18
+ createBranchPolicy(repoInfo: RepoInfo, environment: string, pattern: DeploymentBranchPattern, options?: GhApiOptions): Promise<void>;
19
+ listSecrets(repoInfo: RepoInfo, environment: string, options?: GhApiOptions): Promise<GitHubSecret[]>;
20
+ getSecretsPublicKey(repoInfo: RepoInfo, environment: string, options?: GhApiOptions): Promise<GitHubPublicKey>;
21
+ upsertSecret(repoInfo: RepoInfo, environment: string, name: string, encryptedValue: string, keyId: string, options?: GhApiOptions): Promise<void>;
22
+ }
23
+ export {};
@@ -0,0 +1,54 @@
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
+ const LABEL = "GitHub Environments strategy";
5
+ export class GitHubEnvironmentsStrategy {
6
+ api;
7
+ constructor(executor, options) {
8
+ this.api = new GhApiClient(executor, options.retries ?? 3, options.cwd);
9
+ }
10
+ base(repoInfo, environment) {
11
+ assertGitHubRepo(repoInfo, LABEL);
12
+ const root = `/repos/${repoInfo.owner}/${repoInfo.repo}/environments`;
13
+ return environment === undefined
14
+ ? root
15
+ : `${root}/${encodeURIComponent(environment)}`;
16
+ }
17
+ async list(repoInfo, options) {
18
+ const result = await this.api.call("GET", `${this.base(repoInfo)}?per_page=100`, { options, paginate: true });
19
+ const response = parseApiJson(result, "environments response");
20
+ return (response.environments ?? []).map((env) => ({
21
+ name: env.name,
22
+ deployment_branch_policy: env.deployment_branch_policy ?? null,
23
+ }));
24
+ }
25
+ async createOrUpdate(repoInfo, name, policy, options) {
26
+ await this.api.call("PUT", this.base(repoInfo, name), {
27
+ payload: { deployment_branch_policy: policy },
28
+ options,
29
+ });
30
+ }
31
+ async listBranchPolicies(repoInfo, environment, options) {
32
+ const result = await this.api.call("GET", `${this.base(repoInfo, environment)}/deployment-branch-policies?per_page=100`, { options, paginate: true });
33
+ const response = parseApiJson(result, "deployment branch policies response");
34
+ return (response.branch_policies ?? []).map((p) => ({
35
+ type: p.type ?? "branch",
36
+ name: p.name,
37
+ }));
38
+ }
39
+ async createBranchPolicy(repoInfo, environment, pattern, options) {
40
+ await this.api.call("POST", `${this.base(repoInfo, environment)}/deployment-branch-policies`, { payload: { name: pattern.name, type: pattern.type }, options });
41
+ }
42
+ async listSecrets(repoInfo, environment, options) {
43
+ const result = await this.api.call("GET", `${this.base(repoInfo, environment)}/secrets?per_page=100`, { options, paginate: true });
44
+ const response = parseApiJson(result, "environment secrets response");
45
+ return response.secrets ?? [];
46
+ }
47
+ async getSecretsPublicKey(repoInfo, environment, options) {
48
+ const result = await this.api.call("GET", `${this.base(repoInfo, environment)}/secrets/public-key`, { options });
49
+ return parseApiJson(result, "environment public key response");
50
+ }
51
+ async upsertSecret(repoInfo, environment, name, encryptedValue, keyId, options) {
52
+ await this.api.call("PUT", `${this.base(repoInfo, environment)}/secrets/${encodeURIComponent(name)}`, { payload: { encrypted_value: encryptedValue, key_id: keyId }, options });
53
+ }
54
+ }
@@ -0,0 +1,5 @@
1
+ export { type BranchPolicyKind, type EnvironmentChange, type EnvironmentAction, } from "./diff.js";
2
+ export { type EnvironmentsPlanEntry, type EnvironmentsPlanResult, formatPolicyLine, formatPatternLabel, } from "./formatter.js";
3
+ export { EnvironmentsProcessor, type IEnvironmentsProcessor, type EnvironmentsProcessorResult, } from "./processor.js";
4
+ export { GitHubEnvironmentsStrategy } from "./github-environments-strategy.js";
5
+ export type { IEnvironmentsStrategy, IEnvironmentSecretsStrategy, GitHubEnvironment, GitHubDeploymentBranchPolicy, } from "./types.js";
@@ -0,0 +1,3 @@
1
+ export { formatPolicyLine, formatPatternLabel, } from "./formatter.js";
2
+ export { EnvironmentsProcessor, } from "./processor.js";
3
+ export { GitHubEnvironmentsStrategy } from "./github-environments-strategy.js";
@@ -0,0 +1,21 @@
1
+ import type { RepoConfig } from "../../config/index.js";
2
+ import type { IRepoMetadataProvider, RepoInfo } from "../../repo/index.js";
3
+ import { type EnvironmentsPlanResult } from "./formatter.js";
4
+ import type { IEnvironmentsStrategy } from "./types.js";
5
+ import { type BaseProcessorOptions, type BaseProcessorResult, type ISettingsProcessor, type ChangeCounts } from "../base-processor.js";
6
+ export type IEnvironmentsProcessor = ISettingsProcessor<BaseProcessorOptions, EnvironmentsProcessorResult>;
7
+ export interface EnvironmentsProcessorResult extends BaseProcessorResult {
8
+ changes?: ChangeCounts;
9
+ planOutput?: EnvironmentsPlanResult;
10
+ warnings?: string[];
11
+ }
12
+ export declare class EnvironmentsProcessor implements IEnvironmentsProcessor {
13
+ private readonly strategy;
14
+ private readonly metadataProvider;
15
+ constructor(strategy: IEnvironmentsStrategy, metadataProvider: IRepoMetadataProvider);
16
+ process(repoConfig: RepoConfig, repoInfo: RepoInfo, options: BaseProcessorOptions): Promise<EnvironmentsProcessorResult>;
17
+ private readPatterns;
18
+ private applySettings;
19
+ private applyChange;
20
+ private skipIfNotPublic;
21
+ }