@aspruyt/xfg 8.0.0 → 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 (41) hide show
  1. package/dist/cli/secrets-command.js +12 -2
  2. package/dist/cli/settings-factories.d.ts +2 -1
  3. package/dist/cli/settings-factories.js +7 -1
  4. package/dist/cli/settings-report-builder.d.ts +6 -1
  5. package/dist/cli/settings-report-builder.js +7 -1
  6. package/dist/cli/settings-runner.js +24 -15
  7. package/dist/cli/types.d.ts +4 -2
  8. package/dist/config/index.d.ts +1 -1
  9. package/dist/config/merge.d.ts +9 -5
  10. package/dist/config/merge.js +148 -67
  11. package/dist/config/normalizer.js +87 -18
  12. package/dist/config/types.d.ts +28 -0
  13. package/dist/config/validator.js +17 -3
  14. package/dist/config/validators/ruleset-validator.js +6 -5
  15. package/dist/config/validators/shared.js +123 -0
  16. package/dist/output/settings-report.d.ts +6 -1
  17. package/dist/output/settings-report.js +31 -9
  18. package/dist/settings/environments/diff.d.ts +22 -0
  19. package/dist/settings/environments/diff.js +78 -0
  20. package/dist/settings/environments/formatter.d.ts +17 -0
  21. package/dist/settings/environments/formatter.js +62 -0
  22. package/dist/settings/environments/github-environments-strategy.d.ts +23 -0
  23. package/dist/settings/environments/github-environments-strategy.js +54 -0
  24. package/dist/settings/environments/index.d.ts +5 -0
  25. package/dist/settings/environments/index.js +3 -0
  26. package/dist/settings/environments/processor.d.ts +21 -0
  27. package/dist/settings/environments/processor.js +100 -0
  28. package/dist/settings/environments/types.d.ts +38 -0
  29. package/dist/settings/environments/types.js +1 -0
  30. package/dist/settings/index.d.ts +1 -0
  31. package/dist/settings/index.js +1 -0
  32. package/dist/settings/secrets/diff.d.ts +2 -0
  33. package/dist/settings/secrets/formatter.d.ts +4 -0
  34. package/dist/settings/secrets/formatter.js +17 -4
  35. package/dist/settings/secrets/index.d.ts +2 -2
  36. package/dist/settings/secrets/index.js +1 -1
  37. package/dist/settings/secrets/processor.d.ts +16 -2
  38. package/dist/settings/secrets/processor.js +132 -28
  39. package/dist/shared/sequential.d.ts +2 -0
  40. package/dist/shared/sequential.js +4 -0
  41. package/package.json +2 -2
@@ -1,3 +1,5 @@
1
+ import { runSequentially } from "../../shared/sequential.js";
2
+ import { quoted } from "../../shared/string-utils.js";
1
3
  import { noAppInstallationMessage, } from "../../shared/gh-token-utils.js";
2
4
  import { diffSecrets } from "./diff.js";
3
5
  import { formatSecretsPlan } from "./formatter.js";
@@ -8,29 +10,47 @@ function secretEntriesOf(repoConfig) {
8
10
  {});
9
11
  return Object.entries(entries);
10
12
  }
11
- function hasDesiredSecrets(repoConfig) {
13
+ function hasRepoSecrets(repoConfig) {
12
14
  const s = repoConfig.settings?.secrets ?? {};
13
15
  const { deleteOrphaned, ...entries } = s;
14
16
  return Object.keys(entries).length > 0 || deleteOrphaned === true;
15
17
  }
18
+ function environmentSecretsOf(repoConfig) {
19
+ return Object.entries(repoConfig.settings?.environments ?? {})
20
+ .map(([name, env]) => [
21
+ name,
22
+ Object.entries(env.secrets ?? {}),
23
+ ])
24
+ .filter(([, entries]) => entries.length > 0);
25
+ }
26
+ function missingEnvironmentWarning(repoName, env) {
27
+ return `${repoName}: environment ${quoted(env)} does not exist - its secrets were skipped (environments on private repos need a paid GitHub plan; on a paid plan, run 'xfg sync' first)`;
28
+ }
16
29
  export class SecretsProcessor {
17
30
  strategy;
18
31
  encryptor;
19
32
  envResolver;
20
33
  tokenProvider;
21
- constructor(strategy, encryptor, envResolver, tokenProvider) {
34
+ environments;
35
+ constructor(strategy, encryptor, envResolver, tokenProvider, environments) {
22
36
  this.strategy = strategy;
23
37
  this.encryptor = encryptor;
24
38
  this.envResolver = envResolver;
25
39
  this.tokenProvider = tokenProvider;
40
+ this.environments = environments;
41
+ }
42
+ hasDesiredSecrets(repoConfig) {
43
+ return (hasRepoSecrets(repoConfig) ||
44
+ (this.environments !== undefined &&
45
+ environmentSecretsOf(repoConfig).length > 0));
26
46
  }
27
47
  async process(repoConfig, repoInfo, options) {
28
48
  const result = await withGitHubGuards(repoConfig, repoInfo, options, {
29
- hasDesiredSettings: hasDesiredSecrets,
49
+ hasDesiredSettings: (rc) => this.hasDesiredSecrets(rc),
30
50
  emptySettingsMessage: "No secrets configured",
31
51
  applySettings: (githubRepo, rc, opts, token, repoName) => this.applySettings(githubRepo, rc, opts, token, repoName),
32
52
  });
33
- if (result.skipped && !hasDesiredSecrets(repoConfig)) {
53
+ if (result.skipped && !this.hasDesiredSecrets(repoConfig)) {
34
54
  return { ...result, noSecretsConfigured: true };
35
55
  }
36
56
  return result;
@@ -55,35 +75,54 @@ export class SecretsProcessor {
55
75
  const deleteOrphaned = configDeleteOrphaned && !(noDelete ?? false);
56
76
  const secretEntries = secretEntriesOf(repoConfig).filter((entry) => typeof entry[1] !== "boolean");
57
77
  const strategyOptions = { token, host: githubRepo.host };
58
- const currentSecrets = await this.strategy.list(githubRepo, strategyOptions);
59
- const changes = diffSecrets(currentSecrets, secretEntries.map(([name]) => name), deleteOrphaned);
60
- const changeCounts = countActions(changes);
78
+ const repoChanges = secretEntries.length > 0 || deleteOrphaned
79
+ ? diffSecrets(await this.strategy.list(githubRepo, strategyOptions), secretEntries.map(([name]) => name), deleteOrphaned)
80
+ : [];
81
+ const envGroups = await this.readEnvironments(githubRepo, repoConfig, strategyOptions);
82
+ const envChanges = await this.diffEnvironmentSecrets(githubRepo, envGroups, strategyOptions);
61
83
  if (dryRun) {
62
- return buildDryRunResult(repoName, changeCounts, {
63
- planOutput: formatSecretsPlan(changes, true),
84
+ const planned = [...repoChanges, ...envChanges];
85
+ return buildDryRunResult(repoName, countActions(planned), {
86
+ planOutput: formatSecretsPlan(planned, true),
64
87
  });
65
88
  }
66
- const resolvedValues = secretEntries.length > 0
67
- ? this.envResolver.resolveAll(secretEntries.map(([name, config]) => ({
68
- name,
69
- envVar: config.env,
70
- })))
71
- : new Map();
72
- const publicKey = secretEntries.length > 0
73
- ? await this.strategy.getPublicKey(githubRepo, strategyOptions)
74
- : undefined;
89
+ const gate = await this.gateMissingEnvironments(githubRepo, envGroups, strategyOptions, repoName);
90
+ if (gate.error) {
91
+ return { success: false, repoName, message: `Failed: ${gate.error}` };
92
+ }
93
+ const writableGroups = envGroups.filter((g) => g.exists);
94
+ const writable = new Set(writableGroups.map((g) => g.environment));
95
+ const changes = [
96
+ ...repoChanges,
97
+ ...envChanges.filter((c) => writable.has(c.environment)),
98
+ ];
99
+ const extra = gate.warnings.length > 0 ? { warnings: gate.warnings } : {};
100
+ const repoValues = this.resolve(secretEntries);
101
+ const envValues = writableGroups.map((g) => ({
102
+ environment: g.environment,
103
+ values: this.resolve(g.entries),
104
+ }));
105
+ const scopes = new Map();
106
+ if (secretEntries.length > 0) {
107
+ scopes.set(undefined, {
108
+ values: repoValues,
109
+ publicKey: await this.strategy.getPublicKey(githubRepo, strategyOptions),
110
+ });
111
+ }
112
+ // Serial: GitHub asks for serial requests to avoid secondary rate limits
113
+ await runSequentially(envValues, async ({ environment, values }) => {
114
+ scopes.set(environment, {
115
+ values,
116
+ publicKey: await this.environments.strategy.getSecretsPublicKey(githubRepo, environment, strategyOptions),
117
+ });
118
+ });
75
119
  const applied = [];
76
120
  try {
77
- for (const change of changes.filter(isActiveAction)) {
78
- if (change.action === "delete") {
79
- await this.strategy.delete(githubRepo, change.name, strategyOptions);
80
- }
81
- else {
82
- const encrypted = await this.encryptor.encrypt(resolvedValues.get(change.name), publicKey.key);
83
- await this.strategy.upsert(githubRepo, change.name, encrypted, publicKey.key_id, strategyOptions);
84
- }
121
+ // Serial: GitHub asks for serial requests to avoid secondary rate limits
122
+ await runSequentially(changes.filter(isActiveAction), async (change) => {
123
+ await this.writeChange(githubRepo, change, scopes, strategyOptions);
85
124
  applied.push(change);
86
- }
125
+ });
87
126
  }
88
127
  catch (error) {
89
128
  // Report what already landed: the writes are not rolled back.
@@ -93,10 +132,75 @@ export class SecretsProcessor {
93
132
  message: `Failed: ${toErrorMessage(error)}`,
94
133
  changes: countActions(applied),
95
134
  planOutput: formatSecretsPlan(applied, false),
135
+ ...extra,
96
136
  };
97
137
  }
98
- return buildApplyResult(repoName, changeCounts, applied.length, {
138
+ return buildApplyResult(repoName, countActions(changes), applied.length, {
99
139
  planOutput: formatSecretsPlan(changes, false),
140
+ ...extra,
141
+ });
142
+ }
143
+ async writeChange(githubRepo, change, scopes, strategyOptions) {
144
+ if (change.action === "delete") {
145
+ await this.strategy.delete(githubRepo, change.name, strategyOptions);
146
+ return;
147
+ }
148
+ const { values, publicKey } = scopes.get(change.environment);
149
+ const encrypted = await this.encryptor.encrypt(values.get(change.name), publicKey.key);
150
+ if (change.environment === undefined) {
151
+ await this.strategy.upsert(githubRepo, change.name, encrypted, publicKey.key_id, strategyOptions);
152
+ }
153
+ else {
154
+ await this.environments.strategy.upsertSecret(githubRepo, change.environment, change.name, encrypted, publicKey.key_id, strategyOptions);
155
+ }
156
+ }
157
+ /** On a public repo a missing environment is an error; elsewhere it may be the plan, so warn and skip. */
158
+ async gateMissingEnvironments(githubRepo, groups, strategyOptions, repoName) {
159
+ const missing = groups.filter((g) => !g.exists);
160
+ if (missing.length === 0)
161
+ return { warnings: [] };
162
+ const { visibility } = await this.environments.metadataProvider.getMetadata(githubRepo, strategyOptions);
163
+ if (visibility === "public") {
164
+ return {
165
+ error: `environment ${quoted(missing[0].environment)} does not exist. Run 'xfg sync' first to create it.`,
166
+ warnings: [],
167
+ };
168
+ }
169
+ return {
170
+ warnings: missing.map((g) => missingEnvironmentWarning(repoName, g.environment)),
171
+ };
172
+ }
173
+ resolve(entries) {
174
+ if (entries.length === 0)
175
+ return new Map();
176
+ return this.envResolver.resolveAll(entries.map(([name, config]) => ({ name, envVar: config.env })));
177
+ }
178
+ async readEnvironments(githubRepo, repoConfig, strategyOptions) {
179
+ const configured = this.environments
180
+ ? environmentSecretsOf(repoConfig)
181
+ : [];
182
+ if (configured.length === 0)
183
+ return [];
184
+ const current = await this.environments.strategy.list(githubRepo, strategyOptions);
185
+ const existing = new Map(current.map((env) => [env.name.toLowerCase(), env.name]));
186
+ return configured.map(([name, entries]) => {
187
+ const actual = existing.get(name.toLowerCase());
188
+ return {
189
+ environment: actual ?? name,
190
+ exists: actual !== undefined,
191
+ entries,
192
+ };
193
+ });
194
+ }
195
+ async diffEnvironmentSecrets(githubRepo, groups, strategyOptions) {
196
+ const changes = [];
197
+ // Serial: GitHub asks for serial requests to avoid secondary rate limits
198
+ await runSequentially(groups, async (group) => {
199
+ const current = group.exists
200
+ ? await this.environments.strategy.listSecrets(githubRepo, group.environment, strategyOptions)
201
+ : [];
202
+ changes.push(...diffSecrets(current, group.entries.map(([name]) => name), false).map((change) => ({ ...change, environment: group.environment })));
100
203
  });
204
+ return changes;
101
205
  }
102
206
  }
@@ -0,0 +1,2 @@
1
+ /** Runs `task` for each item one at a time, stopping at the first rejection. */
2
+ export declare function runSequentially<T>(items: readonly T[], task: (item: T) => Promise<void>): Promise<void>;
@@ -0,0 +1,4 @@
1
+ /** Runs `task` for each item one at a time, stopping at the first rejection. */
2
+ export function runSequentially(items, task) {
3
+ return items.reduce((chain, item) => chain.then(() => task(item)), Promise.resolve());
4
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aspruyt/xfg",
3
- "version": "8.0.0",
3
+ "version": "8.1.0",
4
4
  "description": "Manage files, settings, and repositories across GitHub, Azure DevOps, and GitLab — declaratively, from a single YAML config",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -38,7 +38,7 @@
38
38
  "docs:generate": "tsx scripts/docs/generate-docs.ts",
39
39
  "docs:check": "tsx scripts/docs/generate-docs.ts --check",
40
40
  "test": "node --import tsx scripts/run-tests.js",
41
- "test:coverage": "c8 --check-coverage --lines 95 --reporter=text --reporter=lcov --all --src=src --exclude='test/**/*.test.ts' --exclude='scripts/**' --exclude='src/vcs/types.ts' --exclude='src/settings/rulesets/types.ts' --exclude='src/settings/repo-settings/types.ts' --exclude='src/settings/labels/types.ts' --exclude='src/**/index.ts' --exclude='test/mocks/**' --exclude='test/integration/**' --exclude='src/sync/types.ts' --exclude='src/lifecycle/types.ts' --exclude='src/cli/program.ts' --exclude='src/repo/types.ts' --exclude='src/settings/secrets/types.ts' --exclude='src/settings/code-scanning/types.ts' --exclude='src/settings/variables/types.ts' --exclude='src/settings/collaborators/types.ts' --exclude='src/ai/types.ts' --exclude='src/cli/types.ts' --exclude='src/cli.ts' --exclude='src/index.ts' npm test",
41
+ "test:coverage": "c8 --check-coverage --lines 95 --reporter=text --reporter=lcov --all --src=src --exclude='test/**/*.test.ts' --exclude='scripts/**' --exclude='src/vcs/types.ts' --exclude='src/settings/rulesets/types.ts' --exclude='src/settings/repo-settings/types.ts' --exclude='src/settings/labels/types.ts' --exclude='src/**/index.ts' --exclude='test/mocks/**' --exclude='test/integration/**' --exclude='src/sync/types.ts' --exclude='src/lifecycle/types.ts' --exclude='src/cli/program.ts' --exclude='src/repo/types.ts' --exclude='src/settings/secrets/types.ts' --exclude='src/settings/code-scanning/types.ts' --exclude='src/settings/variables/types.ts' --exclude='src/settings/collaborators/types.ts' --exclude='src/settings/environments/types.ts' --exclude='src/ai/types.ts' --exclude='src/cli/types.ts' --exclude='src/cli.ts' --exclude='src/index.ts' npm test",
42
42
  "test:integration:ci": "node --import tsx --test",
43
43
  "test:integration:github": "npm run build && node --import tsx --test test/integration/github.test.ts",
44
44
  "test:integration:ado": "npm run build && node --import tsx --test test/integration/ado.test.ts",