@intentius/chant 0.124.14 → 0.124.16

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 (178) hide show
  1. package/dist/build.d.ts +6 -0
  2. package/dist/build.d.ts.map +1 -1
  3. package/dist/build.js +1 -0
  4. package/dist/change-set.d.ts +24 -2
  5. package/dist/change-set.d.ts.map +1 -1
  6. package/dist/change-set.js +50 -1
  7. package/dist/ci-jobs.d.ts +227 -0
  8. package/dist/ci-jobs.d.ts.map +1 -0
  9. package/dist/ci-jobs.js +448 -0
  10. package/dist/cli/flush.d.ts +16 -0
  11. package/dist/cli/flush.d.ts.map +1 -0
  12. package/dist/cli/flush.js +42 -0
  13. package/dist/cli/handlers/approve.d.ts +98 -0
  14. package/dist/cli/handlers/approve.d.ts.map +1 -0
  15. package/dist/cli/handlers/approve.js +495 -0
  16. package/dist/cli/handlers/operator.d.ts +1 -95
  17. package/dist/cli/handlers/operator.d.ts.map +1 -1
  18. package/dist/cli/handlers/operator.js +4 -488
  19. package/dist/cli/handlers/override-approve.js +1 -1
  20. package/dist/cli/main.d.ts +4 -15
  21. package/dist/cli/main.d.ts.map +1 -1
  22. package/dist/cli/main.js +4 -1062
  23. package/dist/cli/parse-args.d.ts +6 -0
  24. package/dist/cli/parse-args.d.ts.map +1 -0
  25. package/dist/cli/parse-args.js +1028 -0
  26. package/dist/components/fan-out-record.d.ts +1 -1
  27. package/dist/components/fan-out-record.d.ts.map +1 -1
  28. package/dist/components/fan-out-record.js +3 -7
  29. package/dist/components/fan-out-run.d.ts +5 -3
  30. package/dist/components/fan-out-run.d.ts.map +1 -1
  31. package/dist/components/fan-out-run.js +7 -5
  32. package/dist/components/pr-pipeline.d.ts.map +1 -1
  33. package/dist/components/pr-pipeline.js +3 -2
  34. package/dist/composite.d.ts +10 -2
  35. package/dist/composite.d.ts.map +1 -1
  36. package/dist/composite.js +8 -0
  37. package/dist/discovery/collect.d.ts +2 -1
  38. package/dist/discovery/collect.d.ts.map +1 -1
  39. package/dist/discovery/collect.js +16 -1
  40. package/dist/discovery/fold-import.d.ts.map +1 -1
  41. package/dist/discovery/fold-import.js +2 -107
  42. package/dist/discovery/host-composite.d.ts +35 -0
  43. package/dist/discovery/host-composite.d.ts.map +1 -0
  44. package/dist/discovery/host-composite.js +93 -0
  45. package/dist/discovery/index.d.ts +9 -0
  46. package/dist/discovery/index.d.ts.map +1 -1
  47. package/dist/discovery/index.js +1 -1
  48. package/dist/gate-decision.d.ts +20 -9
  49. package/dist/gate-decision.d.ts.map +1 -1
  50. package/dist/gate-decision.js +72 -19
  51. package/dist/gated-waves.d.ts +25 -6
  52. package/dist/gated-waves.d.ts.map +1 -1
  53. package/dist/gated-waves.js +21 -6
  54. package/dist/lifecycle/gate-audit.d.ts +69 -2
  55. package/dist/lifecycle/gate-audit.d.ts.map +1 -1
  56. package/dist/lifecycle/gate-audit.js +76 -2
  57. package/dist/lifecycle/gate-ledger.d.ts +24 -0
  58. package/dist/lifecycle/gate-ledger.d.ts.map +1 -1
  59. package/dist/lifecycle/gate-ledger.js +9 -1
  60. package/dist/op/activities/activity-contracts.d.ts +5 -5
  61. package/dist/op/activities/activity-contracts.js +1 -1
  62. package/dist/op/activities/change-set.d.ts +8 -3
  63. package/dist/op/activities/change-set.d.ts.map +1 -1
  64. package/dist/op/activities/change-set.js +5 -2
  65. package/dist/op/activities/reconcile.d.ts +28 -16
  66. package/dist/op/activities/reconcile.d.ts.map +1 -1
  67. package/dist/op/activities/reconcile.js +34 -20
  68. package/dist/op/builders.d.ts +1 -1
  69. package/dist/op/builders.d.ts.map +1 -1
  70. package/dist/op/builders.js +1 -1
  71. package/dist/op/op-waves-run.d.ts +2 -2
  72. package/dist/op/op-waves-run.d.ts.map +1 -1
  73. package/dist/op/op-waves-run.js +8 -9
  74. package/dist/op/op-waves.d.ts.map +1 -1
  75. package/dist/op/op-waves.js +4 -8
  76. package/dist/package-version.d.ts +2 -0
  77. package/dist/package-version.d.ts.map +1 -0
  78. package/dist/package-version.js +10 -0
  79. package/dist/wave-engine.d.ts +62 -0
  80. package/dist/wave-engine.d.ts.map +1 -0
  81. package/dist/wave-engine.js +59 -0
  82. package/dist/wave-layout.d.ts +29 -0
  83. package/dist/wave-layout.d.ts.map +1 -0
  84. package/dist/wave-layout.js +41 -0
  85. package/dist/wave-runtime.d.ts +29 -0
  86. package/dist/wave-runtime.d.ts.map +1 -0
  87. package/dist/wave-runtime.js +103 -0
  88. package/dist/wave-runtime.mjs +331 -0
  89. package/dist/workspace/__fixtures__/contract-repo.d.ts +7 -0
  90. package/dist/workspace/__fixtures__/contract-repo.d.ts.map +1 -1
  91. package/dist/workspace/__fixtures__/contract-repo.js +17 -1
  92. package/dist/workspace/__fixtures__/sessions.d.ts +1 -1
  93. package/dist/workspace/__fixtures__/sessions.d.ts.map +1 -1
  94. package/dist/workspace/__fixtures__/sessions.js +3 -3
  95. package/dist/workspace/ajv2020.d.ts +5 -0
  96. package/dist/workspace/ajv2020.d.ts.map +1 -0
  97. package/dist/workspace/ajv2020.js +14 -0
  98. package/dist/workspace/change-set.schema.json +5 -3
  99. package/dist/workspace/ci-green-workflow.d.ts +3 -1
  100. package/dist/workspace/ci-green-workflow.d.ts.map +1 -1
  101. package/dist/workspace/ci-green-workflow.js +5 -2
  102. package/dist/workspace/class-data.d.ts +84 -0
  103. package/dist/workspace/class-data.d.ts.map +1 -0
  104. package/dist/workspace/class-data.js +238 -0
  105. package/dist/workspace/declaration.d.ts.map +1 -1
  106. package/dist/workspace/declaration.js +4 -8
  107. package/dist/workspace/kinds.d.ts +3 -7
  108. package/dist/workspace/kinds.d.ts.map +1 -1
  109. package/dist/workspace/kinds.js +8 -45
  110. package/dist/workspace/points.d.ts.map +1 -1
  111. package/dist/workspace/points.js +2 -5
  112. package/dist/workspace/principal-classes.d.ts +4 -11
  113. package/dist/workspace/principal-classes.d.ts.map +1 -1
  114. package/dist/workspace/principal-classes.js +13 -99
  115. package/package.json +5 -3
  116. package/src/build.ts +8 -0
  117. package/src/change-set.test.ts +48 -0
  118. package/src/change-set.ts +52 -2
  119. package/src/ci-jobs.test.ts +49 -0
  120. package/src/ci-jobs.ts +515 -0
  121. package/src/cli/flush.ts +44 -0
  122. package/src/cli/handlers/approve.ts +618 -0
  123. package/src/cli/handlers/operator.ts +10 -608
  124. package/src/cli/handlers/override-approve.test.ts +1 -1
  125. package/src/cli/handlers/override-approve.ts +1 -1
  126. package/src/cli/main.ts +5 -816
  127. package/src/cli/parse-args.ts +781 -0
  128. package/src/components/fan-out-record.ts +3 -7
  129. package/src/components/fan-out-run.ts +7 -5
  130. package/src/components/pr-pipeline.ts +3 -2
  131. package/src/composite.ts +15 -3
  132. package/src/discovery/collect.ts +15 -1
  133. package/src/discovery/fold-build-parity.test.ts +71 -0
  134. package/src/discovery/fold-import.ts +2 -113
  135. package/src/discovery/fold-project-provenance.test.ts +21 -4
  136. package/src/discovery/host-composite.ts +101 -0
  137. package/src/discovery/index.ts +11 -1
  138. package/src/gate-decision-bundle.test.ts +6 -4
  139. package/src/gate-decision-identity.test.ts +59 -6
  140. package/src/gate-decision.ts +81 -21
  141. package/src/gated-waves.ts +28 -6
  142. package/src/lifecycle/gate-audit.test.ts +55 -1
  143. package/src/lifecycle/gate-audit.ts +116 -3
  144. package/src/lifecycle/gate-ledger.test.ts +20 -1
  145. package/src/lifecycle/gate-ledger.ts +33 -1
  146. package/src/op/activities/activity-contracts.ts +1 -1
  147. package/src/op/activities/change-set.ts +11 -3
  148. package/src/op/activities/lexicon-upgrade.test.ts +2 -0
  149. package/src/op/activities/reconcile.test.ts +62 -2
  150. package/src/op/activities/reconcile.ts +46 -22
  151. package/src/op/builders.ts +1 -1
  152. package/src/op/op-waves-run.ts +9 -9
  153. package/src/op/op-waves.test.ts +2 -0
  154. package/src/op/op-waves.ts +4 -8
  155. package/src/op/work-lease-run.test.ts +12 -4
  156. package/src/package-version.ts +11 -0
  157. package/src/wave-engine.test.ts +107 -0
  158. package/src/wave-engine.ts +98 -0
  159. package/src/wave-layout.ts +44 -0
  160. package/src/wave-runtime-bundle.test.ts +70 -0
  161. package/src/wave-runtime.e2e.test.ts +177 -0
  162. package/src/wave-runtime.ts +104 -0
  163. package/src/workspace/__fixtures__/contract-repo.ts +17 -1
  164. package/src/workspace/__fixtures__/sessions.ts +3 -3
  165. package/src/workspace/ajv2020.ts +17 -0
  166. package/src/workspace/change-set.schema.json +5 -3
  167. package/src/workspace/ci-green-workflow.test.ts +4 -4
  168. package/src/workspace/ci-green-workflow.ts +5 -2
  169. package/src/workspace/class-data.test.ts +64 -0
  170. package/src/workspace/class-data.ts +236 -0
  171. package/src/workspace/declaration.ts +4 -10
  172. package/src/workspace/kinds.ts +8 -40
  173. package/src/workspace/points.ts +2 -5
  174. package/src/workspace/principal-classes.ts +13 -99
  175. package/src/workspace/records-formats.test.ts +7 -2
  176. package/src/workspace/records-sessions-write.test.ts +3 -3
  177. package/src/workspace/status-contract.e2e.test.ts +37 -0
  178. package/src/workspace/status-contract.test.ts +23 -21
@@ -0,0 +1,49 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import {
3
+ assertGitlabBranch,
4
+ CI_IMAGE,
5
+ gitlabRules,
6
+ githubSecret,
7
+ githubSecretEnv,
8
+ githubSecretOrJobToken,
9
+ pushBranches,
10
+ triggerBranches,
11
+ } from "./ci-jobs";
12
+ import { PR_LOOP_IMAGE } from "./components/pr-pipeline";
13
+
14
+ describe("the job primitives the CI generators share (#3765)", () => {
15
+ test("one default image, which the pull-request pipeline uses too", () => {
16
+ expect(CI_IMAGE).toBe("node:22");
17
+ expect(PR_LOOP_IMAGE).toBe(CI_IMAGE);
18
+ });
19
+
20
+ test("a push trigger with no branches, or an empty list, filters on main; a pull_request trigger then takes every branch", () => {
21
+ expect(pushBranches(undefined)).toEqual(["main"]);
22
+ expect(pushBranches([])).toEqual(["main"]);
23
+ expect(pushBranches(["trunk"])).toEqual(["trunk"]);
24
+ expect(triggerBranches({ kind: "push", branches: [] })).toEqual(["main"]);
25
+ expect(triggerBranches({ kind: "pull_request", branches: [] })).toBeUndefined();
26
+ expect(triggerBranches({ kind: "pull_request", branches: ["main"] })).toEqual(["main"]);
27
+ expect(triggerBranches({ kind: "cron", schedule: "0 * * * *" })).toBeUndefined();
28
+ });
29
+
30
+ test("a secret, and a secret that falls back to the job token when unset (#3624)", () => {
31
+ expect(githubSecret("T")).toBe("${{ secrets.T }}");
32
+ expect(githubSecretOrJobToken("T")).toBe("${{ secrets.T || github.token }}");
33
+ expect(githubSecretEnv(["A", "B"])).toEqual({ A: "${{ secrets.A }}", B: "${{ secrets.B }}" });
34
+ });
35
+
36
+ test("GitLab rules: one entry per branch, and a branch that would break the expression is refused", () => {
37
+ const selector = { variable: "CHANT_SCHEDULED_OP", value: "watch" };
38
+ expect(gitlabRules("Scheduled Op \"apply\"", { kind: "push", branches: ["main", "prod"] }, selector)).toEqual([
39
+ { if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "main"' },
40
+ { if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "prod"' },
41
+ ]);
42
+ expect(gitlabRules("x", { kind: "pull_request", branches: [] }, selector)).toEqual([{ if: '$CI_PIPELINE_SOURCE == "merge_request_event"' }]);
43
+ expect(gitlabRules("x", { kind: "cron", schedule: "0 * * * *" }, selector)).toEqual([
44
+ { if: '$CI_PIPELINE_SOURCE == "schedule" && $CHANT_SCHEDULED_OP == "watch"' },
45
+ ]);
46
+ expect(() => assertGitlabBranch("Op waves \"w\"", "a$b")).toThrow(/Op waves "w" filters on branch "a\$b"/);
47
+ expect(() => assertGitlabBranch("Op waves \"w\"", " ")).toThrow(/empty branch filter/);
48
+ });
49
+ });
package/src/ci-jobs.ts ADDED
@@ -0,0 +1,515 @@
1
+ /**
2
+ * The job primitives chant's three CI generators share (#3765): the scheduled
3
+ * Op pipeline (`generateOpsPipeline`), the Op waves pipeline
4
+ * (`generateOpWavesPipeline`) and the component pipeline (`chant build
5
+ * --components --generate`, with `--pr-loop`, `--wave-gate` and
6
+ * `--promote-to`). Each forge lexicon builds its documents from these, so a
7
+ * trigger, a token, a permission rule or an image default is decided once:
8
+ *
9
+ * - the image a generated job runs in, {@link CI_IMAGE};
10
+ * - the branches a trigger filters on, {@link triggerBranches};
11
+ * - the job token and secret expressions of GitHub Actions and Forgejo
12
+ * Actions, {@link GITHUB_JOB_TOKEN} and {@link githubSecret};
13
+ * - the `permissions:` a finding-mode needs and the rules for adding to it,
14
+ * {@link permissionsFor} and {@link mergePermissions};
15
+ * - the `setup` steps and `environment` a job may carry, checked once per
16
+ * forge ({@link assertSetupSteps}, {@link assertEnvironment},
17
+ * {@link gitlabSetupScript}, {@link assertGitlabEnvironment});
18
+ * - GitLab's `rules:` expressions and `id_tokens:` declaration.
19
+ *
20
+ * The Forgejo dialect (action refs, dropped `permissions:` and
21
+ * `environment:`, the header note naming what was dropped) is the forgejo
22
+ * lexicon's, in its `components/ci-jobs.ts`, since the transform it applies
23
+ * lives there.
24
+ */
25
+
26
+ import type { OpEnvironment, OpFindingMode, OpSetupStep, OpTrigger } from "./lexicon";
27
+
28
+ // ── Every forge ─────────────────────────────────────────────────────────────
29
+
30
+ /**
31
+ * The image every generated job runs in unless the caller names another. It
32
+ * carries node and npm, which `chant` needs, and git, which a job that reads
33
+ * the base commit or pushes to `chant/lifecycle` needs (#3789).
34
+ */
35
+ export const CI_IMAGE = "node:22";
36
+
37
+ /**
38
+ * The branch a `push` trigger filters on when it names none. A generator
39
+ * works from a spec, not a checkout, so it cannot read a project's real
40
+ * default branch; a project on another one names it.
41
+ */
42
+ export const DEFAULT_BRANCH = "main";
43
+
44
+ /**
45
+ * The branches a push trigger filters on: the ones given, or
46
+ * {@link DEFAULT_BRANCH} when none are. An empty list is none, on every
47
+ * forge.
48
+ */
49
+ export function pushBranches(branches: readonly string[] | undefined): string[] {
50
+ return branches && branches.length > 0 ? [...branches] : [DEFAULT_BRANCH];
51
+ }
52
+
53
+ /**
54
+ * The branches a trigger filters on: a `pull_request` trigger's list, or
55
+ * undefined for every branch; a `push` trigger's, with {@link pushBranches}'
56
+ * default; none for `cron`.
57
+ */
58
+ export function triggerBranches(trigger: OpTrigger): string[] | undefined {
59
+ switch (trigger.kind) {
60
+ case "cron":
61
+ return undefined;
62
+ case "pull_request":
63
+ return trigger.branches && trigger.branches.length > 0 ? [...trigger.branches] : undefined;
64
+ case "push":
65
+ return pushBranches(trigger.branches);
66
+ }
67
+ }
68
+
69
+ /** A job id every forge accepts, from a kebab- or camel-cased name. */
70
+ export function ciJobName(name: string): string {
71
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
72
+ }
73
+
74
+ /** A command template with each `{name}` part filled in. */
75
+ export function fillCommand(template: readonly string[], name: string): string[] {
76
+ return template.map((part) => part.replace("{name}", name));
77
+ }
78
+
79
+ /** `{ [key]: map }` when the map has an entry, else `{}`: for spreading an optional mapping into a document. */
80
+ export function nonEmpty<K extends string, V>(key: K, map: Record<string, V> | undefined): { [P in K]?: Record<string, V> } {
81
+ return map && Object.keys(map).length > 0 ? ({ [key]: map } as { [P in K]: Record<string, V> }) : {};
82
+ }
83
+
84
+ /**
85
+ * A job's `environment:` mapping. Always the mapping form, never the string
86
+ * shorthand, so adding a `url` later is a new key rather than a reshaped
87
+ * value. GitHub and GitLab read the same two keys.
88
+ */
89
+ export function environmentDoc(environment: OpEnvironment): { name: string; url?: string } {
90
+ return { name: environment.name, ...(environment.url === undefined ? {} : { url: environment.url }) };
91
+ }
92
+
93
+ /** The directory part of a relative path, `.` when there is none. */
94
+ export function dirnameOf(path: string): string {
95
+ const i = path.lastIndexOf("/");
96
+ return i <= 0 ? "." : path.slice(0, i);
97
+ }
98
+
99
+ // ── GitHub Actions and Forgejo Actions ──────────────────────────────────────
100
+
101
+ /** The runner label a generated job asks for; the Forgejo dialect rewrites it to the project's label. */
102
+ export const GITHUB_RUNNER = "ubuntu-latest";
103
+
104
+ /** The job token, which GitHub and Forgejo both mint for every run. */
105
+ export const GITHUB_JOB_TOKEN = "${{ github.token }}";
106
+
107
+ /** A repository secret, by name. */
108
+ export function githubSecret(name: string): string {
109
+ return `\${{ secrets.${name} }}`;
110
+ }
111
+
112
+ /**
113
+ * A repository secret, or the job token when the secret is unset (#3624). An
114
+ * unset secret reads as the empty string, so a workflow generated for a
115
+ * production token still runs in a fork or a fresh repository, with what the
116
+ * job token may do.
117
+ */
118
+ export function githubSecretOrJobToken(name: string): string {
119
+ return `\${{ secrets.${name} || github.token }}`;
120
+ }
121
+
122
+ /** Each name mapped from the repository secret of the same name. */
123
+ export function githubSecretEnv(names: readonly string[]): Record<string, string> {
124
+ return Object.fromEntries(names.map((n) => [n, githubSecret(n)]));
125
+ }
126
+
127
+ /**
128
+ * Least-privilege `permissions:` for a finding-mode. `report` needs no write
129
+ * access; `issue` needs only `issues: write`; `pull-request` (and
130
+ * `merge-request`, generated the same way when a GitLab-authored spec is
131
+ * targeted at github) needs `contents: write` to push the reconcile branch
132
+ * plus `pull-requests: write` to open the PR. `comment` changes nothing in
133
+ * the repository, so its whole scope is `{ contents: read, pull-requests:
134
+ * write }`.
135
+ */
136
+ export function permissionsForMode(mode: OpFindingMode): Record<string, "read" | "write"> {
137
+ switch (mode) {
138
+ case "issue":
139
+ return { contents: "read", issues: "write" };
140
+ case "comment":
141
+ return { contents: "read", "pull-requests": "write" };
142
+ case "pull-request":
143
+ case "merge-request":
144
+ return { contents: "write", "pull-requests": "write" };
145
+ case "report":
146
+ return { contents: "read" };
147
+ }
148
+ }
149
+
150
+ /**
151
+ * {@link permissionsForMode} on a trigger. A `pull_request` trigger reports
152
+ * its finding as a comment on the triggering PR itself (#2084): any mode but
153
+ * `report` posts something to act on a finding, so on that trigger every
154
+ * such mode also gets `pull-requests: write` for the comment.
155
+ */
156
+ export function permissionsFor(mode: OpFindingMode, trigger: OpTrigger): Record<string, "read" | "write"> {
157
+ const base = permissionsForMode(mode);
158
+ if (trigger.kind === "pull_request" && mode !== "report") return { ...base, "pull-requests": "write" };
159
+ return base;
160
+ }
161
+
162
+ /**
163
+ * Every scope `GITHUB_TOKEN` accepts in a workflow's `permissions:` mapping,
164
+ * kebab-cased as GitHub spells them. An additive scope outside this set is
165
+ * refused by name rather than emitted: GitHub ignores an unknown key, so
166
+ * `id_token` or `idToken` would generate a workflow that looks like it grants
167
+ * OIDC and hands the run no token at all.
168
+ */
169
+ export const GITHUB_TOKEN_SCOPES: ReadonlySet<string> = new Set([
170
+ "actions",
171
+ "attestations",
172
+ "checks",
173
+ "contents",
174
+ "deployments",
175
+ "discussions",
176
+ "id-token",
177
+ "issues",
178
+ "models",
179
+ "packages",
180
+ "pages",
181
+ "pull-requests",
182
+ "repository-projects",
183
+ "security-events",
184
+ "statuses",
185
+ ]);
186
+
187
+ /**
188
+ * Merge a spec's additive `permissions` over the finding-mode's own set
189
+ * (#2242), refusing by name anything that is not strictly additive:
190
+ *
191
+ * - a blanket `write-all`/`read-all`, in either the key or the value
192
+ * position, which is the exact thing {@link permissionsForMode} exists to
193
+ * avoid;
194
+ * - a scope GitHub does not define ({@link GITHUB_TOKEN_SCOPES}), because
195
+ * GitHub ignores the key and the run silently gets nothing;
196
+ * - a scope the mode already grants, at any value — additive means additive,
197
+ * so this can neither downgrade `contents: write` to read nor restate it.
198
+ * A mode whose set is wrong is fixed by changing the mode, where the
199
+ * scope and the behavior that spends it stay together;
200
+ * - `pull-requests: write` on a trigger with no pull request. Pull-request
201
+ * access is what the finding-modes own: `pull-request` grants it together
202
+ * with the `contents: write` needed to push the branch first, and
203
+ * `comment` grants it on the one trigger that carries a pull request to
204
+ * comment on. Adding it beside a mode that posts nothing, on a cron or
205
+ * push run, grants write access no step in the generated job can spend.
206
+ */
207
+ export function mergePermissions(
208
+ name: string,
209
+ base: Record<string, "read" | "write">,
210
+ additive: Record<string, "read" | "write">,
211
+ trigger: OpTrigger,
212
+ ): Record<string, "read" | "write"> {
213
+ const merged: Record<string, "read" | "write"> = { ...base };
214
+ for (const [rawScope, value] of Object.entries(additive)) {
215
+ const scope = rawScope.trim();
216
+ const where = `Scheduled Op "${name}" adds permission "${scope}: ${value}"`;
217
+ if (scope === "write-all" || scope === "read-all" || String(value).endsWith("-all")) {
218
+ throw new Error(
219
+ `${where}, a blanket grant. \`permissions\` on a scheduled Op is additive over the ` +
220
+ `least-privilege set its finding-mode needs, one named scope at a time. Name the scopes the ` +
221
+ `job actually spends (e.g. { "id-token": "write" }).`,
222
+ );
223
+ }
224
+ if (!GITHUB_TOKEN_SCOPES.has(scope)) {
225
+ throw new Error(
226
+ `${where}, which is not a GITHUB_TOKEN permission scope. GitHub ignores an unrecognized key, so ` +
227
+ `this would emit a workflow that reads as granted and hands the run nothing. Known scopes: ` +
228
+ `${[...GITHUB_TOKEN_SCOPES].sort().join(", ")}.`,
229
+ );
230
+ }
231
+ if (scope in base) {
232
+ throw new Error(
233
+ `${where}, but its finding-mode already grants "${scope}: ${base[scope]}". These permissions are ` +
234
+ `additive only — they never replace, widen or downgrade a scope the mode computed. Change the ` +
235
+ `Op's findingMode if that set is wrong, and add only scopes no mode grants (e.g. "id-token").`,
236
+ );
237
+ }
238
+ if (scope === "pull-requests" && trigger.kind !== "pull_request") {
239
+ throw new Error(
240
+ `${where}, but this Op's trigger is "${trigger.kind}", which carries no pull request. Pull-request ` +
241
+ `write access belongs to a finding-mode: "pull-request" grants it with the contents: write its ` +
242
+ `branch push needs, and "comment" grants it on the pull_request trigger. Set findingMode instead ` +
243
+ `of adding the scope here.`,
244
+ );
245
+ }
246
+ merged[scope] = value;
247
+ }
248
+ return merged;
249
+ }
250
+
251
+ /**
252
+ * Refs that name an action repository's own default branch. A generated
253
+ * workflow is committed once and then re-run unattended, often over a cloud
254
+ * role, so "whatever was pushed to that repo last" is not a version — the
255
+ * code that assumes the role can change between the run somebody reviewed and
256
+ * the next one. A release channel the action's author cuts deliberately (`v6`,
257
+ * `v6.2.4`, `stable`) or a commit sha is a version, and both pass.
258
+ */
259
+ const DEFAULT_BRANCH_REFS = new Set(["main", "master", "head", "default"]);
260
+
261
+ /** `owner/repo` or `owner/repo/subpath`, then `@ref`. */
262
+ const USES_PATTERN = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)((?:\/[A-Za-z0-9_.-]+)*)@([^\s@]+)$/;
263
+
264
+ /**
265
+ * Validate a `setup` list for GitHub or Forgejo Actions (#2242). A `run`
266
+ * entry needs a non-empty line and nothing else. A `uses` entry has to be a
267
+ * pinned `owner/repo[/subpath]@ref`: no bare `owner/repo`, since an unpinned
268
+ * action resolves to its default branch, and no ref in
269
+ * {@link DEFAULT_BRANCH_REFS} for the same reason spelled out loud. Local
270
+ * (`./path`) and container (`docker://`) refs are refused too — they are
271
+ * legal GitHub Actions, but the generator emits a workflow into a repository
272
+ * it has never seen, so it cannot know a local path resolves there.
273
+ */
274
+ export function assertSetupSteps(name: string, setup: OpSetupStep[]): void {
275
+ setup.forEach((step, index) => {
276
+ const where = `Scheduled Op "${name}" setup step ${index + 1}`;
277
+ if ("uses" in step) {
278
+ const ref = step.uses.trim();
279
+ const match = USES_PATTERN.exec(ref);
280
+ if (!match) {
281
+ throw new Error(
282
+ `${where} has \`uses: "${step.uses}"\`, which is not a pinned action reference. ` +
283
+ `Write it as owner/repo@ref (optionally owner/repo/subpath@ref), e.g. ` +
284
+ `"aws-actions/configure-aws-credentials@v6". A local "./path" or "docker://" ref is not ` +
285
+ `accepted here: this generator emits a workflow into a repository it cannot inspect, so it ` +
286
+ `has no way to tell whether such a ref resolves there.`,
287
+ );
288
+ }
289
+ const gitRef = match[4];
290
+ if (DEFAULT_BRANCH_REFS.has(gitRef.toLowerCase())) {
291
+ throw new Error(
292
+ `${where} pins \`uses: "${step.uses}"\` to "${gitRef}", the action repository's own default ` +
293
+ `branch, which names whatever was pushed there last rather than a version. A generated ` +
294
+ `workflow is committed once and re-run unattended, often over a cloud role, so pin a release ` +
295
+ `tag or a commit sha instead (e.g. "${match[1]}/${match[2]}@v1" or "@<40-char sha>").`,
296
+ );
297
+ }
298
+ return;
299
+ }
300
+ if (step.run.trim() === "") {
301
+ throw new Error(`${where} has an empty \`run\` line. Give it a command, or drop the entry.`);
302
+ }
303
+ });
304
+ }
305
+
306
+ /** One setup entry as a GitHub Actions step: `with:` and `env:` only when they hold something. */
307
+ export function setupStepDoc(step: OpSetupStep): Record<string, unknown> {
308
+ if ("uses" in step) {
309
+ return {
310
+ uses: step.uses,
311
+ ...nonEmpty("with", step.with),
312
+ ...nonEmpty("env", step.env),
313
+ };
314
+ }
315
+ return { run: step.run, ...nonEmpty("env", step.env) };
316
+ }
317
+
318
+ /**
319
+ * Validate an `environment` for GitHub Actions (#2257). GitHub creates an
320
+ * environment it has never seen on first use rather than failing the run,
321
+ * and an environment created that way carries no protection rules at all —
322
+ * so a job can name one and read as gated while being gated by nothing.
323
+ * Neither the generator nor GitHub can tell those apart at build time, which
324
+ * is why what is refused here is only the shape that could never bind: a
325
+ * name that is blank, and a `url` that is neither absolute nor an expression
326
+ * the forge resolves.
327
+ */
328
+ export function assertEnvironment(name: string, environment: OpEnvironment): void {
329
+ const where = `Scheduled Op "${name}" environment`;
330
+ if (environment.name.trim() === "") {
331
+ throw new Error(
332
+ `${where} has an empty \`name\`. An environment is named repository configuration — the ` +
333
+ `protection rules and reviewers live on the environment, not in this workflow — so there is ` +
334
+ `nothing for a blank name to resolve to. Give it the environment's name, or drop the option.`,
335
+ );
336
+ }
337
+ if (environment.url === undefined) return;
338
+ const url = environment.url.trim();
339
+ if (url === "") {
340
+ throw new Error(`${where} "${environment.name}" has an empty \`url\`. Omit the field rather than setting it to "".`);
341
+ }
342
+ if (!/^https?:\/\//.test(url) && !url.includes("${{")) {
343
+ throw new Error(
344
+ `${where} "${environment.name}" has \`url: "${environment.url}"\`, which is neither an absolute ` +
345
+ `http(s) URL nor a \${{ }} expression. GitHub renders this value as the deployment's own link, ` +
346
+ `so a relative path becomes a dead link on the environment page rather than an error anywhere. ` +
347
+ `Write the full URL, or an expression the run resolves to one.`,
348
+ );
349
+ }
350
+ }
351
+
352
+ // ── GitLab CI ───────────────────────────────────────────────────────────────
353
+
354
+ /** The pipeline source GitLab reports for a merge-request pipeline. */
355
+ export const GITLAB_MERGE_REQUEST_SOURCE = '$CI_PIPELINE_SOURCE == "merge_request_event"';
356
+
357
+ /** The pipeline source GitLab reports for a pipeline schedule. */
358
+ export const GITLAB_SCHEDULE_SOURCE = '$CI_PIPELINE_SOURCE == "schedule"';
359
+
360
+ /** A job variable that makes the runner clone the whole history, which a job reading the base commit needs. */
361
+ export const GITLAB_FULL_HISTORY = { GIT_DEPTH: "0" } as const;
362
+
363
+ /** The `rules:` if-expression for a push to `branch`, a quoted name or an expression such as `$CI_DEFAULT_BRANCH`. */
364
+ export function gitlabPushRule(branch: string): string {
365
+ return `$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == ${branch}`;
366
+ }
367
+
368
+ /**
369
+ * Refuse a branch name that cannot be interpolated into a `rules:`
370
+ * if-expression. The expression is a string GitLab parses, so a `"` would end
371
+ * it early and a `$` would expand as a variable — either one silently changes
372
+ * which pipelines match the job, which is worse than not generating it.
373
+ * `subject` names what filters, such as `Scheduled Op "apply"`.
374
+ */
375
+ export function assertGitlabBranch(subject: string, branch: string): void {
376
+ if (branch.trim() === "") {
377
+ throw new Error(`${subject} has an empty branch filter. Name a branch, or drop the filter.`);
378
+ }
379
+ if (/["$\\]/.test(branch)) {
380
+ throw new Error(
381
+ `${subject} filters on branch "${branch}", which carries a character this generator ` +
382
+ `cannot put in a GitLab \`rules:\` expression: a quote would end the expression early and a "$" ` +
383
+ `would expand as a CI/CD variable, either of which silently changes which pipelines run the job. ` +
384
+ `Name a branch without \`"\`, \`$\` or \`\\\`.`,
385
+ );
386
+ }
387
+ }
388
+
389
+ /**
390
+ * One `rules:` entry per branch a trigger filters on, each checked by
391
+ * {@link assertGitlabBranch}. Two or more branches are two or more entries:
392
+ * `rules:` is an OR over its list, which is how GitLab spells the alternation
393
+ * github expresses as a `branches:` array. A cron trigger is selected by
394
+ * `selector`, the CI/CD variable a pipeline schedule sets, and the Op's name.
395
+ */
396
+ export function gitlabRules(subject: string, trigger: OpTrigger, selector: { variable: string; value: string }): Array<{ if: string }> {
397
+ switch (trigger.kind) {
398
+ case "cron":
399
+ return [{ if: `${GITLAB_SCHEDULE_SOURCE} && $${selector.variable} == "${selector.value}"` }];
400
+ case "pull_request": {
401
+ const branches = triggerBranches(trigger);
402
+ if (!branches) return [{ if: GITLAB_MERGE_REQUEST_SOURCE }];
403
+ return branches.map((branch) => {
404
+ assertGitlabBranch(subject, branch);
405
+ return { if: `${GITLAB_MERGE_REQUEST_SOURCE} && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "${branch}"` };
406
+ });
407
+ }
408
+ case "push":
409
+ return pushBranches(trigger.branches).map((branch) => {
410
+ assertGitlabBranch(subject, branch);
411
+ return { if: gitlabPushRule(JSON.stringify(branch)) };
412
+ });
413
+ }
414
+ }
415
+
416
+ /**
417
+ * The `id_tokens:` entry an `id-token: write` spec gets. The name is the
418
+ * environment variable the JWT lands in, which the job's own setup line reads
419
+ * (`aws sts assume-role-with-web-identity --web-identity-token
420
+ * "$CHANT_ID_TOKEN"`, or the provider's equivalent).
421
+ *
422
+ * `$CI_SERVER_URL` as the audience is GitLab's own documented default: an
423
+ * identity provider federated to a GitLab instance is registered with that
424
+ * instance's URL as its audience, and the variable expands to exactly that on
425
+ * gitlab.com and on a self-managed instance alike.
426
+ */
427
+ export const GITLAB_ID_TOKEN_NAME = "CHANT_ID_TOKEN";
428
+ export const GITLAB_ID_TOKEN_AUDIENCE = "$CI_SERVER_URL";
429
+
430
+ /**
431
+ * Turn additive `permissions` (#2242) into the one GitLab declaration that
432
+ * carries the same meaning, refusing everything else by name.
433
+ *
434
+ * `id-token: write` is that one: GitLab's OIDC surface is `id_tokens:`, a
435
+ * per-job declaration of a JWT the job exchanges for cloud credentials
436
+ * itself. `id-token: read` is refused rather than mapped, because GitLab
437
+ * either mints the token into the job or does not. Every other scope is
438
+ * refused: GitLab has no per-job token-scope mapping at all, and a scope
439
+ * quietly dropped would emit a job that reads as granted and runs with
440
+ * nothing.
441
+ */
442
+ export function gitlabIdTokens(name: string, permissions: Record<string, "read" | "write"> | undefined): Record<string, unknown> | undefined {
443
+ let wantsIdToken = false;
444
+ for (const [rawScope, value] of Object.entries(permissions ?? {})) {
445
+ const scope = rawScope.trim();
446
+ if (scope === "id-token") {
447
+ if (value !== "write") {
448
+ throw new Error(
449
+ `Scheduled Op "${name}" adds permission "id-token: ${value}", but GitLab either mints an ` +
450
+ `OIDC token into a job or does not — there is no read-only half of an \`id_tokens:\` ` +
451
+ `declaration. Ask for { "id-token": "write" }, or drop the option.`,
452
+ );
453
+ }
454
+ wantsIdToken = true;
455
+ continue;
456
+ }
457
+ throw new Error(
458
+ `Scheduled Op "${name}" adds permission "${scope}: ${value}", but GitLab CI has no per-job ` +
459
+ `token-scope mapping — there is no \`permissions:\` key to add it to (#2242). The one scope that ` +
460
+ `does cross over is "id-token": "write", which becomes an \`id_tokens:\` declaration. Drop the ` +
461
+ `option here, or generate this Op for github.`,
462
+ );
463
+ }
464
+ return wantsIdToken ? { [GITLAB_ID_TOKEN_NAME]: { aud: GITLAB_ID_TOKEN_AUDIENCE } } : undefined;
465
+ }
466
+
467
+ /**
468
+ * A `setup` list as GitLab `script:` lines. A `uses` entry is a GitHub
469
+ * Actions marketplace action, which GitLab has no shape for, so it is refused
470
+ * by name rather than dropped. `subject` names whose setup it is, such as
471
+ * `Scheduled Op "apply"`.
472
+ */
473
+ export function gitlabSetupScript(subject: string, setup: readonly OpSetupStep[] | undefined): string[] {
474
+ return (setup ?? []).map((step, index) => {
475
+ if ("uses" in step) {
476
+ throw new Error(
477
+ `${subject} setup step ${index + 1} is \`uses: "${step.uses}"\`, a GitHub Actions ` +
478
+ `marketplace action. GitLab CI jobs run \`script\` lines only, so there is nothing to translate it ` +
479
+ `into (#2242). Express the setup as a \`{ run }\` entry, or generate it for github/forgejo.`,
480
+ );
481
+ }
482
+ return step.run;
483
+ });
484
+ }
485
+
486
+ /**
487
+ * Validate an `environment` on GitLab's own terms (#2257). A GitLab job
488
+ * naming an environment that does not exist creates an unprotected one on
489
+ * first deploy rather than failing, so the only shapes worth refusing at
490
+ * build time are the ones that could never bind: a blank name, and a `url`
491
+ * that is neither absolute nor a variable expression GitLab expands, which
492
+ * would render as a dead "View deployment" link.
493
+ */
494
+ export function assertGitlabEnvironment(name: string, environment: OpEnvironment): void {
495
+ const where = `Scheduled Op "${name}" environment`;
496
+ if (environment.name.trim() === "") {
497
+ throw new Error(
498
+ `${where} has an empty \`name\`. A GitLab environment is a project object, and its approval ` +
499
+ `rules live on that object rather than in this file, so a blank name resolves to nothing. ` +
500
+ `Give it the environment's name, or drop the option.`,
501
+ );
502
+ }
503
+ if (environment.url === undefined) return;
504
+ const url = environment.url.trim();
505
+ if (url === "") {
506
+ throw new Error(`${where} "${environment.name}" has an empty \`url\`. Omit the field rather than setting it to "".`);
507
+ }
508
+ if (!/^https?:\/\//.test(url) && !url.includes("$")) {
509
+ throw new Error(
510
+ `${where} "${environment.name}" has \`url: "${environment.url}"\`, which is neither an absolute ` +
511
+ `http(s) URL nor a variable expression GitLab expands. It becomes the environment's own link, ` +
512
+ `so a relative path is a dead link on the environment page rather than an error anywhere.`,
513
+ );
514
+ }
515
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Exiting without truncating piped output, shared by the full CLI (`./main.ts`)
3
+ * and the slim wave-job runtime (`../wave-runtime.ts`, #3896).
4
+ */
5
+
6
+ /**
7
+ * Wait until a writable stream has flushed its buffer. `process.exit()` discards
8
+ * data still buffered for an async sink (a pipe or file), truncating large output
9
+ * at the ~64 KB pipe buffer — so `chant graph --format ir` piped into a consumer
10
+ * loses everything past 64 KB and its JSON won't parse. A TTY writes
11
+ * synchronously (`writableLength` stays 0), so this is a no-op there. Resolves on
12
+ * `error`/`close` too, so a reader that closes early (EPIPE) can't hang exit.
13
+ */
14
+ export function waitForStreamDrain(stream: NodeJS.WriteStream): Promise<void> {
15
+ return new Promise((resolve) => {
16
+ const tick = (): void => {
17
+ if (stream.writableLength === 0 || stream.writableEnded || stream.destroyed) {
18
+ cleanup();
19
+ resolve();
20
+ return;
21
+ }
22
+ stream.once("drain", tick);
23
+ };
24
+ const stop = (): void => {
25
+ cleanup();
26
+ resolve();
27
+ };
28
+ const cleanup = (): void => {
29
+ stream.off("drain", tick);
30
+ stream.off("error", stop);
31
+ stream.off("close", stop);
32
+ };
33
+ stream.once("error", stop);
34
+ stream.once("close", stop);
35
+ tick();
36
+ });
37
+ }
38
+
39
+ /** Flush stdout+stderr, then exit — so a large piped payload isn't truncated. */
40
+ export async function flushAndExit(code: number): Promise<never> {
41
+ await waitForStreamDrain(process.stdout);
42
+ await waitForStreamDrain(process.stderr);
43
+ process.exit(code);
44
+ }