@intentius/chant 0.124.85 → 0.124.86

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 (254) hide show
  1. package/dist/bundle-check.d.ts +102 -0
  2. package/dist/bundle-check.d.ts.map +1 -0
  3. package/dist/bundle-check.js +310 -0
  4. package/dist/chant-install.d.ts +100 -0
  5. package/dist/chant-install.d.ts.map +1 -0
  6. package/dist/chant-install.js +158 -0
  7. package/dist/ci-commit.d.ts +19 -6
  8. package/dist/ci-commit.d.ts.map +1 -1
  9. package/dist/ci-commit.js +23 -4
  10. package/dist/ci-evidence-jobs.d.ts +54 -0
  11. package/dist/ci-evidence-jobs.d.ts.map +1 -0
  12. package/dist/ci-evidence-jobs.js +55 -0
  13. package/dist/ci-image.d.ts +274 -0
  14. package/dist/ci-image.d.ts.map +1 -0
  15. package/dist/ci-image.js +635 -0
  16. package/dist/ci-login.d.ts +150 -0
  17. package/dist/ci-login.d.ts.map +1 -0
  18. package/dist/ci-login.js +240 -0
  19. package/dist/ci-product.d.ts +16 -0
  20. package/dist/ci-product.d.ts.map +1 -1
  21. package/dist/ci-product.js +17 -0
  22. package/dist/cli/commands/import-index.js +2 -2
  23. package/dist/cli/handlers/build.d.ts +8 -0
  24. package/dist/cli/handlers/build.d.ts.map +1 -1
  25. package/dist/cli/handlers/build.js +22 -4
  26. package/dist/cli/handlers/ci-check.d.ts.map +1 -1
  27. package/dist/cli/handlers/ci-check.js +57 -2
  28. package/dist/cli/handlers/ci-evidence.d.ts +3 -0
  29. package/dist/cli/handlers/ci-evidence.d.ts.map +1 -0
  30. package/dist/cli/handlers/ci-evidence.js +171 -0
  31. package/dist/cli/handlers/components.js +3 -3
  32. package/dist/cli/handlers/dead-guards.d.ts +3 -0
  33. package/dist/cli/handlers/dead-guards.d.ts.map +1 -0
  34. package/dist/cli/handlers/dead-guards.js +35 -0
  35. package/dist/cli/handlers/graph.js +4 -4
  36. package/dist/cli/handlers/lifecycle.d.ts +2 -1
  37. package/dist/cli/handlers/lifecycle.d.ts.map +1 -1
  38. package/dist/cli/handlers/lifecycle.js +5 -4
  39. package/dist/cli/handlers/local-chant.d.ts +16 -0
  40. package/dist/cli/handlers/local-chant.d.ts.map +1 -0
  41. package/dist/cli/handlers/local-chant.js +109 -0
  42. package/dist/cli/handlers/operator.js +2 -2
  43. package/dist/cli/handlers/search.js +5 -5
  44. package/dist/cli/main.d.ts.map +1 -1
  45. package/dist/cli/main.js +38 -0
  46. package/dist/cli/parse-args.d.ts.map +1 -1
  47. package/dist/cli/parse-args.js +28 -0
  48. package/dist/cli/registry.d.ts +16 -0
  49. package/dist/cli/registry.d.ts.map +1 -1
  50. package/dist/components/check-hooks.d.ts +49 -0
  51. package/dist/components/check-hooks.d.ts.map +1 -1
  52. package/dist/components/check-hooks.js +64 -4
  53. package/dist/components/check-steps.d.ts +17 -0
  54. package/dist/components/check-steps.d.ts.map +1 -1
  55. package/dist/components/check-steps.js +37 -5
  56. package/dist/components/product-pipeline.d.ts +23 -0
  57. package/dist/components/product-pipeline.d.ts.map +1 -1
  58. package/dist/components/product-pipeline.js +6 -2
  59. package/dist/components/product-plan.d.ts +137 -0
  60. package/dist/components/product-plan.d.ts.map +1 -0
  61. package/dist/components/product-plan.js +143 -0
  62. package/dist/components/release-compile.d.ts.map +1 -1
  63. package/dist/components/release-compile.js +2 -2
  64. package/dist/config.d.ts +39 -1
  65. package/dist/config.d.ts.map +1 -1
  66. package/dist/config.js +35 -3
  67. package/dist/dead-guards.d.ts +82 -0
  68. package/dist/dead-guards.d.ts.map +1 -0
  69. package/dist/dead-guards.js +436 -0
  70. package/dist/discovery/files.d.ts +3 -1
  71. package/dist/discovery/files.d.ts.map +1 -1
  72. package/dist/discovery/files.js +5 -3
  73. package/dist/drift-issue.d.ts +152 -0
  74. package/dist/drift-issue.d.ts.map +1 -0
  75. package/dist/drift-issue.js +167 -0
  76. package/dist/floor-table.d.ts +30 -0
  77. package/dist/floor-table.d.ts.map +1 -0
  78. package/dist/floor-table.data.d.ts +3 -0
  79. package/dist/floor-table.data.d.ts.map +1 -0
  80. package/dist/floor-table.data.js +178 -0
  81. package/dist/floor-table.js +56 -0
  82. package/dist/forge-flags.d.ts +90 -0
  83. package/dist/forge-flags.d.ts.map +1 -0
  84. package/dist/forge-flags.js +184 -0
  85. package/dist/lexicon.d.ts +69 -0
  86. package/dist/lexicon.d.ts.map +1 -1
  87. package/dist/lifecycle/gated-op.d.ts +7 -1
  88. package/dist/lifecycle/gated-op.d.ts.map +1 -1
  89. package/dist/lifecycle/gated-op.js +7 -4
  90. package/dist/local-chant.d.ts +98 -0
  91. package/dist/local-chant.d.ts.map +1 -0
  92. package/dist/local-chant.js +307 -0
  93. package/dist/op/activities/predict-behaviour.js +2 -2
  94. package/dist/op/op-waves-evidence-spec.d.ts +13 -0
  95. package/dist/op/op-waves-evidence-spec.d.ts.map +1 -0
  96. package/dist/op/op-waves-evidence-spec.js +21 -0
  97. package/dist/op/op-waves-evidence.d.ts +38 -0
  98. package/dist/op/op-waves-evidence.d.ts.map +1 -0
  99. package/dist/op/op-waves-evidence.js +57 -0
  100. package/dist/op/op-waves-run.d.ts +4 -0
  101. package/dist/op/op-waves-run.d.ts.map +1 -1
  102. package/dist/op/op-waves-run.js +24 -1
  103. package/dist/op/op-waves.d.ts +17 -1
  104. package/dist/op/op-waves.d.ts.map +1 -1
  105. package/dist/op/op-waves.js +23 -0
  106. package/dist/op/schedule-overdue.d.ts +41 -9
  107. package/dist/op/schedule-overdue.d.ts.map +1 -1
  108. package/dist/op/schedule-overdue.js +154 -25
  109. package/dist/plan-summary.d.ts +25 -0
  110. package/dist/plan-summary.d.ts.map +1 -1
  111. package/dist/plan-summary.js +31 -0
  112. package/dist/pr-plan-note.d.ts +35 -0
  113. package/dist/pr-plan-note.d.ts.map +1 -1
  114. package/dist/pr-plan-note.js +10 -0
  115. package/dist/pr-post.d.ts +23 -0
  116. package/dist/pr-post.d.ts.map +1 -1
  117. package/dist/pr-post.js +125 -3
  118. package/dist/release-floors.d.ts +31 -1
  119. package/dist/release-floors.d.ts.map +1 -1
  120. package/dist/release-floors.js +31 -1
  121. package/dist/state-migration.d.ts +24 -0
  122. package/dist/state-migration.d.ts.map +1 -1
  123. package/dist/state-migration.js +100 -5
  124. package/dist/wave-runtime.mjs +305 -298
  125. package/dist/workspace/lexicon-outputs.d.ts.map +1 -1
  126. package/dist/workspace/lexicon-outputs.js +21 -7
  127. package/dist/workspace/reason-codes.d.ts +3 -0
  128. package/dist/workspace/reason-codes.d.ts.map +1 -1
  129. package/dist/workspace/reason-codes.js +4 -0
  130. package/dist/workspace/ref-gate.schema.json +85 -0
  131. package/dist/workspace/search-contract.d.ts +1 -1
  132. package/dist/workspace/search-contract.d.ts.map +1 -1
  133. package/dist/workspace/trust/check-evidence-report.d.ts +51 -0
  134. package/dist/workspace/trust/check-evidence-report.d.ts.map +1 -0
  135. package/dist/workspace/trust/check-evidence-report.js +102 -0
  136. package/dist/workspace/trust/check-evidence.d.ts +126 -0
  137. package/dist/workspace/trust/check-evidence.d.ts.map +1 -0
  138. package/dist/workspace/trust/check-evidence.js +237 -0
  139. package/dist/workspace/trust/local-evidence.d.ts +120 -0
  140. package/dist/workspace/trust/local-evidence.d.ts.map +1 -0
  141. package/dist/workspace/trust/local-evidence.js +259 -0
  142. package/dist/workspace/trust/policy.d.ts +84 -0
  143. package/dist/workspace/trust/policy.d.ts.map +1 -1
  144. package/dist/workspace/trust/policy.js +94 -1
  145. package/dist/workspace/trust/ref-gate-cli.d.ts +33 -0
  146. package/dist/workspace/trust/ref-gate-cli.d.ts.map +1 -0
  147. package/dist/workspace/trust/ref-gate-cli.js +234 -0
  148. package/dist/workspace/trust/ref-gate-fixture.d.ts +38 -0
  149. package/dist/workspace/trust/ref-gate-fixture.d.ts.map +1 -0
  150. package/dist/workspace/trust/ref-gate-fixture.js +97 -0
  151. package/dist/workspace/trust/ref-gate.d.ts +187 -0
  152. package/dist/workspace/trust/ref-gate.d.ts.map +1 -0
  153. package/dist/workspace/trust/ref-gate.js +430 -0
  154. package/dist/workspace/trust/trust-files.d.ts.map +1 -1
  155. package/dist/workspace/trust/trust-files.js +18 -1
  156. package/package.json +1 -1
  157. package/src/bundle-check.test.ts +140 -0
  158. package/src/bundle-check.ts +352 -0
  159. package/src/chant-install.test.ts +112 -0
  160. package/src/chant-install.ts +179 -0
  161. package/src/ci-commit.test.ts +45 -0
  162. package/src/ci-commit.ts +38 -4
  163. package/src/ci-evidence-jobs.ts +67 -0
  164. package/src/ci-image.test.ts +506 -0
  165. package/src/ci-image.ts +822 -0
  166. package/src/ci-login.test.ts +235 -0
  167. package/src/ci-login.ts +307 -0
  168. package/src/ci-product.ts +18 -0
  169. package/src/cli/commands/__fixtures__/source-dir-include/chant.config.json +1 -0
  170. package/src/cli/commands/__fixtures__/source-dir-include/infra.ts +1 -0
  171. package/src/cli/commands/__fixtures__/source-dir-include/scripts/run-on-load.ts +3 -0
  172. package/src/cli/commands/__fixtures__/source-dir-root/chant.config.json +1 -0
  173. package/src/cli/commands/__fixtures__/source-dir-root/infra.test.ts +1 -0
  174. package/src/cli/commands/__fixtures__/source-dir-root/infra.ts +1 -0
  175. package/src/cli/commands/__fixtures__/source-dir-root/scripts/run-on-load.ts +3 -0
  176. package/src/cli/commands/__fixtures__/source-dir-scoped/app.ts +3 -0
  177. package/src/cli/commands/__fixtures__/source-dir-scoped/chant.config.json +1 -0
  178. package/src/cli/commands/__fixtures__/source-dir-scoped/infra/net.ts +1 -0
  179. package/src/cli/commands/__fixtures__/source-dir-scoped/scripts/run-on-load.ts +3 -0
  180. package/src/cli/commands/import-index.ts +2 -2
  181. package/src/cli/handlers/build-source-dir.test.ts +64 -0
  182. package/src/cli/handlers/build.ts +21 -4
  183. package/src/cli/handlers/ci-check.ts +56 -3
  184. package/src/cli/handlers/ci-evidence.ts +162 -0
  185. package/src/cli/handlers/components.ts +3 -3
  186. package/src/cli/handlers/dead-guards.ts +37 -0
  187. package/src/cli/handlers/graph.ts +4 -4
  188. package/src/cli/handlers/lifecycle.ts +5 -4
  189. package/src/cli/handlers/local-chant.ts +106 -0
  190. package/src/cli/handlers/operator.ts +2 -2
  191. package/src/cli/handlers/search.ts +5 -5
  192. package/src/cli/main.test.ts +7 -0
  193. package/src/cli/main.ts +38 -0
  194. package/src/cli/parse-args.ts +21 -0
  195. package/src/cli/registry.ts +16 -0
  196. package/src/components/check-evidence-stage.test.ts +80 -0
  197. package/src/components/check-hooks.ts +84 -4
  198. package/src/components/check-local-evidence-stage.test.ts +141 -0
  199. package/src/components/check-steps.ts +56 -6
  200. package/src/components/product-pipeline.ts +28 -3
  201. package/src/components/product-plan.test.ts +87 -0
  202. package/src/components/product-plan.ts +226 -0
  203. package/src/components/release-compile.ts +2 -2
  204. package/src/config.ts +44 -3
  205. package/src/dead-guards.test.ts +206 -0
  206. package/src/dead-guards.ts +446 -0
  207. package/src/discovery/files.ts +5 -3
  208. package/src/drift-issue-bundle.test.ts +31 -0
  209. package/src/drift-issue.test.ts +206 -0
  210. package/src/drift-issue.ts +274 -0
  211. package/src/fit-note.test.ts +44 -0
  212. package/src/floor-table.data.ts +180 -0
  213. package/src/floor-table.ts +77 -0
  214. package/src/forge-flags.test.ts +110 -0
  215. package/src/forge-flags.ts +208 -0
  216. package/src/gate-decision-bundle.test.ts +1 -0
  217. package/src/lexicon.ts +68 -0
  218. package/src/lifecycle/gated-op.ts +10 -5
  219. package/src/local-chant.e2e.test.ts +94 -0
  220. package/src/local-chant.test.ts +162 -0
  221. package/src/local-chant.ts +341 -0
  222. package/src/op/activities/predict-behaviour.ts +2 -2
  223. package/src/op/op-waves-evidence-spec.ts +24 -0
  224. package/src/op/op-waves-evidence.test.ts +130 -0
  225. package/src/op/op-waves-evidence.ts +57 -0
  226. package/src/op/op-waves-run.ts +25 -1
  227. package/src/op/op-waves.ts +31 -1
  228. package/src/op/schedule-overdue.test.ts +85 -0
  229. package/src/op/schedule-overdue.ts +162 -26
  230. package/src/plan-summary.ts +40 -0
  231. package/src/pr-plan-note.ts +34 -0
  232. package/src/pr-post-plan-note.test.ts +146 -0
  233. package/src/pr-post.ts +127 -3
  234. package/src/release-floors.ts +44 -1
  235. package/src/stage-hooks-bundle.test.ts +1 -0
  236. package/src/state-migration.test.ts +52 -1
  237. package/src/state-migration.ts +107 -5
  238. package/src/workspace/lexicon-outputs.ts +23 -6
  239. package/src/workspace/reason-codes.test.ts +3 -0
  240. package/src/workspace/reason-codes.ts +4 -0
  241. package/src/workspace/ref-gate.schema.json +85 -0
  242. package/src/workspace/trust/check-evidence-report.ts +106 -0
  243. package/src/workspace/trust/check-evidence.test.ts +133 -0
  244. package/src/workspace/trust/check-evidence.ts +257 -0
  245. package/src/workspace/trust/local-evidence.test.ts +127 -0
  246. package/src/workspace/trust/local-evidence.ts +266 -0
  247. package/src/workspace/trust/policy.ts +134 -1
  248. package/src/workspace/trust/ref-gate-cli.ts +244 -0
  249. package/src/workspace/trust/ref-gate-fixture.ts +125 -0
  250. package/src/workspace/trust/ref-gate.e2e.test.ts +76 -0
  251. package/src/workspace/trust/ref-gate.test.ts +247 -0
  252. package/src/workspace/trust/ref-gate.ts +538 -0
  253. package/src/workspace/trust/trust-files.test.ts +16 -0
  254. package/src/workspace/trust/trust-files.ts +41 -1
@@ -0,0 +1,208 @@
1
+ /**
2
+ * #4800 — the forge target from a product's flags, over the job's
3
+ * environment.
4
+ *
5
+ * SQL Yodeler's `--forge`, `--repo`, `--pr`, `--api-url` and `--token-env`,
6
+ * terragucci's target built from a configured origin and path, and plywood's
7
+ * `--forge` each turned into {@link forgeTargetFromEnv}'s input their own
8
+ * way. {@link forgeTargetWith} is {@link forgeTargetFromEnv} with overrides
9
+ * for the repository, the pull request, the REST base and the web origin,
10
+ * and {@link forgeTargetFromFlags} takes them as the strings a command line
11
+ * gives and checks them first.
12
+ *
13
+ * The overrides are written into a copy of the environment as the variables
14
+ * {@link forgeTargetFromEnv} reads, so its reading stays the one reading.
15
+ * They live here, not in `pr-forge.ts`, because that file is in the pr-forge
16
+ * and pr-loop bundles, which have no room for them.
17
+ */
18
+
19
+ import { detectForge, FORGE_KINDS, FORGE_TOKEN_ORDER, ForgeEnvironmentError, forgeTargetFromEnv, type ForgeKind, type ForgeTarget, type ForgeTargetOptions } from "./pr-forge";
20
+
21
+ /** What {@link forgeTargetWith} takes over the environment. */
22
+ export interface ForgeOverrides {
23
+ /** `--repo`: `owner/name`, or the GitLab project id or path. */
24
+ repo?: string;
25
+ /** `--pr`: the pull or merge request. Its head is then the job's commit, not the event's. */
26
+ pr?: number;
27
+ /** `--api-url`: the REST base. Without `url`, its host is the target's. */
28
+ apiUrl?: string;
29
+ /** `--url`: the forge's web origin. It gives the host, and the REST base ({@link apiBaseOf}) when `apiUrl` is not given. */
30
+ url?: string;
31
+ /** Return a target with an empty token when none is set, which reads a public repository. Default false. */
32
+ tokenOptional?: boolean;
33
+ }
34
+
35
+ const trimUrl = (u: string | undefined): string | undefined => u?.trim().replace(/\/+$/, "") || undefined;
36
+
37
+ const hostOf = (url: string): string | undefined => {
38
+ try {
39
+ return new URL(url).host.toLowerCase();
40
+ } catch {
41
+ return undefined;
42
+ }
43
+ };
44
+
45
+ /**
46
+ * A forge's REST base from its web origin (terragucci's `apiBase`):
47
+ * `https://api.github.com` for github.com, `<url>/api/v3` for another
48
+ * GitHub host, `<url>/api/v4` on GitLab, `<url>/api/v1` on Forgejo.
49
+ */
50
+ export function apiBaseOf(kind: ForgeKind, url: string): string {
51
+ const origin = trimUrl(url) ?? url;
52
+ if (kind === "gitlab") return `${origin}/api/v4`;
53
+ if (kind === "forgejo") return `${origin}/api/v1`;
54
+ return hostOf(origin) === "github.com" ? "https://api.github.com" : `${origin}/api/v3`;
55
+ }
56
+
57
+ /** The variable a given or placeholder token is put in for {@link forgeTargetFromEnv} to read. */
58
+ const GIVEN_TOKEN = "CHANT_GIVEN_FORGE_TOKEN";
59
+
60
+ /**
61
+ * {@link forgeTargetFromEnv} with `overrides` over what the environment
62
+ * says (#4800); a run outside CI passes all of them with `kind`. The run's
63
+ * URL stays the job's own, since the run is the job's whatever it posts to.
64
+ * Throws {@link ForgeEnvironmentError} as {@link forgeTargetFromEnv} does.
65
+ */
66
+ export function forgeTargetWith(env: Record<string, string | undefined> = process.env, opts: ForgeTargetOptions & ForgeOverrides = {}): ForgeTarget {
67
+ const { repo: repoIn, pr, apiUrl: apiIn, url: urlIn, tokenOptional, ...base } = opts;
68
+ const kind = base.kind ?? detectForge(env);
69
+ if (!kind) throw new ForgeEnvironmentError(undefined, []);
70
+ const repo = repoIn?.trim() || undefined;
71
+ const url = trimUrl(urlIn);
72
+ const apiUrl = trimUrl(apiIn) ?? (url ? apiBaseOf(kind, url) : undefined);
73
+ const prRef = pr !== undefined && pr > 0 ? pr : undefined;
74
+ const e: Record<string, string | undefined> = { ...env };
75
+ const fj = kind === "forgejo";
76
+ const job = (name: string): string | undefined => (fj ? env[`FORGEJO_${name}`]?.trim() || undefined : undefined) ?? (env[`GITHUB_${name}`]?.trim() || undefined);
77
+ if (kind === "gitlab") {
78
+ if (repo) e.CI_MERGE_REQUEST_PROJECT_ID = e.CI_PROJECT_ID = repo;
79
+ if (prRef) e.CI_MERGE_REQUEST_IID = String(prRef);
80
+ if (apiUrl) e.CI_API_V4_URL = apiUrl;
81
+ if (url) e.CI_SERVER_URL = url;
82
+ if (url || apiUrl) e.CI_SERVER_HOST = hostOf(url ?? apiUrl!);
83
+ } else {
84
+ // A Forgejo job reads FORGEJO_* before GITHUB_*, so an override sets both.
85
+ const set = (name: string, value: string | undefined): void => {
86
+ e[`GITHUB_${name}`] = value;
87
+ e[`FORGEJO_${name}`] = value;
88
+ };
89
+ if (repo) set("REPOSITORY", repo);
90
+ if (apiUrl) set("API_URL", apiUrl);
91
+ if (url) set("SERVER_URL", url);
92
+ if (prRef) {
93
+ // The event payload names the pull request before the ref does.
94
+ set("EVENT_PATH", undefined);
95
+ set("REF", `refs/pull/${prRef}/merge`);
96
+ }
97
+ }
98
+ const names = base.tokenEnv ? [base.tokenEnv] : FORGE_TOKEN_ORDER[kind];
99
+ const noToken = tokenOptional === true && !names.some((n) => e[n]?.trim());
100
+ if (noToken) e[GIVEN_TOKEN] = "-";
101
+ const t = forgeTargetFromEnv(e, { ...base, kind, ...(noToken ? { tokenEnv: GIVEN_TOKEN } : {}) });
102
+ const out: ForgeTarget = { ...t };
103
+ if (noToken) Object.assign(out, { token: "", tokenSource: "" });
104
+ if (kind !== "gitlab" && apiUrl && !url) out.host = hostOf(apiUrl)!.replace(/^api\.github\.com$/, "github.com");
105
+ if (kind !== "gitlab" && (repo || url)) {
106
+ const server = trimUrl(job("SERVER_URL"));
107
+ const jobRepo = job("REPOSITORY");
108
+ const runId = job("RUN_ID");
109
+ if (server && jobRepo && runId) out.runUrl = `${server}/${jobRepo}/actions/runs/${runId}`;
110
+ else delete out.runUrl;
111
+ }
112
+ return out;
113
+ }
114
+
115
+ /** A product's forge flags, as strings from its command line, and what it read from its config. */
116
+ export interface ForgeFlags {
117
+ /** `--forge`: github, gitlab or forgejo, over {@link detectForge}. */
118
+ forge?: string;
119
+ /** `--repo`: `owner/name`, or the GitLab project id or path. */
120
+ repo?: string;
121
+ /** `--pr`: the pull or merge request number. */
122
+ pr?: string | number;
123
+ /** `--api-url`: the REST base. */
124
+ apiUrl?: string;
125
+ /** `--url`: the forge's web origin, which gives the host and, without `--api-url`, the REST base. */
126
+ url?: string;
127
+ /** `--token-env`: the one variable to read the token from. */
128
+ tokenEnv?: string;
129
+ /** A token the product already holds (read from its own config's variable). Never a flag. */
130
+ token?: string;
131
+ }
132
+
133
+ /** A flag {@link forgeTargetFromFlags} refuses, named in the message. */
134
+ export class ForgeFlagError extends Error {
135
+ constructor(
136
+ readonly flag: string,
137
+ message: string,
138
+ ) {
139
+ super(message);
140
+ this.name = "ForgeFlagError";
141
+ }
142
+ }
143
+
144
+ const set = (v: string | undefined): string | undefined => (v === undefined || v.trim() === "" ? undefined : v.trim());
145
+
146
+ /**
147
+ * The checked flags as {@link forgeTargetWith}'s options: `--forge` one of
148
+ * {@link FORGE_KINDS}, `--pr` a positive whole number, `--url` and
149
+ * `--api-url` http or https URLs. Throws {@link ForgeFlagError}.
150
+ */
151
+ export function forgeTargetOptionsFromFlags(flags: ForgeFlags): ForgeTargetOptions & ForgeOverrides {
152
+ const out: ForgeTargetOptions & ForgeOverrides = {};
153
+ const forge = set(flags.forge);
154
+ if (forge !== undefined) {
155
+ if (!(FORGE_KINDS as readonly string[]).includes(forge)) throw new ForgeFlagError("--forge", `--forge must be one of ${FORGE_KINDS.join(", ")}, got ${JSON.stringify(flags.forge)}`);
156
+ out.kind = forge as ForgeKind;
157
+ }
158
+ const repo = set(flags.repo);
159
+ if (repo !== undefined) out.repo = repo;
160
+ if (flags.pr !== undefined && String(flags.pr).trim() !== "") {
161
+ const pr = String(flags.pr).trim();
162
+ if (!/^[1-9]\d*$/.test(pr)) throw new ForgeFlagError("--pr", `--pr must be a pull request number, got ${JSON.stringify(flags.pr)}`);
163
+ out.pr = Number(pr);
164
+ }
165
+ for (const [flag, key] of [["--api-url", "apiUrl"], ["--url", "url"]] as const) {
166
+ const v = set(flags[key]);
167
+ if (v === undefined) continue;
168
+ if (!/^https?:\/\/[^/\s]+/i.test(v)) throw new ForgeFlagError(flag, `${flag} must be an http or https URL, got ${JSON.stringify(flags[key])}`);
169
+ out[key] = v;
170
+ }
171
+ const tokenEnv = set(flags.tokenEnv);
172
+ if (tokenEnv !== undefined) out.tokenEnv = tokenEnv;
173
+ return out;
174
+ }
175
+
176
+ /**
177
+ * Where a command posts: {@link forgeTargetWith} with the checked flags.
178
+ * `opts` carries the rest (`requirePr`, `tokenOptional`, `readFile`). A
179
+ * forge neither `--forge` nor the environment names throws
180
+ * {@link ForgeEnvironmentError} with no kind; a missing piece throws it with
181
+ * the pieces, and {@link forgeFlagHints} names the flags that supply them.
182
+ */
183
+ export function forgeTargetFromFlags(
184
+ flags: ForgeFlags,
185
+ env: Record<string, string | undefined> = process.env,
186
+ opts: Pick<ForgeTargetOptions, "requirePr" | "readFile"> & Pick<ForgeOverrides, "tokenOptional"> = {},
187
+ ): ForgeTarget {
188
+ const fromFlags = forgeTargetOptionsFromFlags(flags);
189
+ const token = set(flags.token);
190
+ if (token === undefined) return forgeTargetWith(env, { ...opts, ...fromFlags });
191
+ // The token came from the product, not a variable; say so rather than name chant's.
192
+ const t = forgeTargetWith({ ...env, [GIVEN_TOKEN]: token }, { ...opts, ...fromFlags, tokenEnv: GIVEN_TOKEN });
193
+ return { ...t, tokenSource: "the token given" };
194
+ }
195
+
196
+ /**
197
+ * The flags that would supply what a {@link ForgeEnvironmentError} says is
198
+ * missing, for a product's message: `outside CI pass --repo, --pr and
199
+ * --api-url` and `name another token variable with --token-env`.
200
+ */
201
+ export function forgeFlagHints(e: ForgeEnvironmentError, options: { requirePr?: boolean; tokenEnv?: boolean } = {}): string[] {
202
+ const token = e.missing.some((m) => m.startsWith("a token"));
203
+ const other = e.kind === undefined || e.missing.some((m) => !m.startsWith("a token"));
204
+ return [
205
+ ...(other ? [`outside CI pass ${e.kind === undefined ? "--forge github|gitlab|forgejo, " : ""}${options.requirePr ? "--repo, --pr and --api-url" : "--repo and --api-url"}`] : []),
206
+ ...(token && !options.tokenEnv ? ["name another token variable with --token-env"] : []),
207
+ ];
208
+ }
@@ -59,6 +59,7 @@ describe("the gate-decision bundle", () => {
59
59
  "packages/core/src/op/gate-quorum.ts",
60
60
  // The step and holds settings checks (#4545), with no run-time imports.
61
61
  "packages/core/src/op/op-waves-capability-spec.ts",
62
+ "packages/core/src/op/op-waves-evidence-spec.ts",
62
63
  // The release names a wave writes (#4615), checked with the spec.
63
64
  "packages/core/src/op/op-waves-release.ts",
64
65
  "packages/core/src/op/op-waves.ts",
package/src/lexicon.ts CHANGED
@@ -1147,6 +1147,74 @@ export interface OpWavesPipelineOptions
1147
1147
  * `OP_WAVE_JOB_TIMEOUT_MINUTES` (180).
1148
1148
  */
1149
1149
  jobTimeoutMinutes?: number;
1150
+ /**
1151
+ * What a product adds to each wave's jobs, keyed by wave name (#4791): a
1152
+ * login before the job's command and a report after it, with the files
1153
+ * the report writes. A product passes them here instead of parsing the
1154
+ * generated file and editing it. A name that is not one of the spec's
1155
+ * waves is refused. Absent: the jobs render as without it.
1156
+ */
1157
+ waveJobs?: Record<string, OpWaveJobInputs>;
1158
+ /**
1159
+ * What a product adds to the plans job, `record-plans` (#4791), which a
1160
+ * `pr-review` or `pull-request` wave adds: the steps before it plans
1161
+ * (a login, a check that the job cannot write), its variables and its
1162
+ * OIDC tokens. Absent: the job renders as without it.
1163
+ */
1164
+ recordPlans?: OpWavesRecordPlansInputs;
1165
+ /**
1166
+ * The pipeline's runner identity (#4870): the secret (GitHub, Forgejo) or
1167
+ * CI/CD variable (GitLab) holding the runner key `.chant/trust.json`
1168
+ * lists. Each deciding wave job's `chant run wave` step gets it as
1169
+ * `CHANT_RUNNER_KEY` and signs `plan:<wave>` and `policy:<wave>` once the
1170
+ * wave is planned. Absent: the jobs render as without it.
1171
+ */
1172
+ evidence?: import("./ci-evidence-jobs").PipelineEvidence;
1173
+ }
1174
+
1175
+ /** A run step a product adds to a generated job (#4791): its name, and its shell lines in order. */
1176
+ export interface OpWaveRunStep {
1177
+ name: string;
1178
+ run: string[];
1179
+ }
1180
+
1181
+ /** What a product adds to each job of one wave (#4791, {@link OpWavesPipelineOptions.waveJobs}). */
1182
+ export interface OpWaveJobInputs {
1183
+ /**
1184
+ * Steps run just before the job's command, after `beforeScript`, such as
1185
+ * a cloud login. GitHub and Forgejo: one step each, its lines joined by
1186
+ * newlines. GitLab: their lines in the job's script. With the wave's
1187
+ * `cloud`, they run after the token request is unset, as every later step.
1188
+ */
1189
+ before?: OpWaveRunStep[];
1190
+ /**
1191
+ * A step run after the job whatever its exit, since a wave that waits at
1192
+ * its gate exits 3. GitHub and Forgejo: a step with `if: always()` after
1193
+ * the job's own steps. GitLab: its lines are the job's `after_script`.
1194
+ */
1195
+ report?: OpWaveRunStep;
1196
+ /**
1197
+ * Files the job keeps as an artifact whatever its exit. `{job}` in
1198
+ * `name` is the job's name, so a wide wave's jobs keep one each. GitHub
1199
+ * and Forgejo: an upload step named `step` after the report. GitLab: the
1200
+ * path joins the job's `artifacts:`, which keep the outcome files too,
1201
+ * under `name`.
1202
+ */
1203
+ artifact?: { step: string; name: string; path: string };
1204
+ }
1205
+
1206
+ /** What a product adds to the plans job, `record-plans` (#4791, {@link OpWavesPipelineOptions.recordPlans}). */
1207
+ export interface OpWavesRecordPlansInputs {
1208
+ /** Steps run just before the job plans, after `beforeScript`, as {@link OpWaveJobInputs.before}. */
1209
+ before?: OpWaveRunStep[];
1210
+ /** The job's own variables: GitHub and Forgejo `env:`, GitLab `variables:`. */
1211
+ variables?: Record<string, string>;
1212
+ /**
1213
+ * OIDC tokens the job requests, `{ <variable>: <audience> }` as a wave's
1214
+ * `idTokens`: GitLab `id_tokens:`; on GitHub and Forgejo the job asks for
1215
+ * `id-token: write` and gets each audience as `<NAME>_AUDIENCE`.
1216
+ */
1217
+ idTokens?: Record<string, string>;
1150
1218
  }
1151
1219
 
1152
1220
  /** An Op waves pipeline: one file, and its jobs in order. */
@@ -39,20 +39,23 @@ export const chantGatedLedger: GatedRequestLedger = { requestGate, spendGatedReq
39
39
  /**
40
40
  * The time a request was first asked, so asking again binds the same
41
41
  * digest. The newest standing, unspent request with the same kind, subject,
42
- * requester and fields gives its `at`; with none, `now`.
42
+ * requester and fields gives its `at`; with none, `now`. With `reuseApplied`
43
+ * (#4808) a request that applied already counts too, so the same call asked
44
+ * again answers `spent` rather than asking anew: a retried job never acts
45
+ * twice on one approval.
43
46
  */
44
47
  export async function requestedAt(
45
48
  op: string,
46
49
  request: Omit<GatedRequest, "at">,
47
- options: { now?: string; cwd?: string; ledger?: Pick<GatedRequestLedger, "readGatedRequests"> } = {},
50
+ options: { now?: string; cwd?: string; ledger?: Pick<GatedRequestLedger, "readGatedRequests">; reuseApplied?: boolean } = {},
48
51
  ): Promise<string> {
49
52
  const now = options.now ?? new Date().toISOString();
50
53
  const read = await (options.ledger ?? chantGatedLedger).readGatedRequests(op, options.cwd ? { cwd: options.cwd } : undefined).catch(() => []);
51
54
  const same = JSON.stringify(Object.entries(request.fields).sort());
52
55
  const standing = read
53
- .filter((g) => !g.applied && g.request.kind === request.kind && g.request.subject === request.subject && g.request.by === request.by)
56
+ .filter((g) => (options.reuseApplied || !g.applied) && g.request.kind === request.kind && g.request.subject === request.subject && g.request.by === request.by)
54
57
  .filter((g) => JSON.stringify(Object.entries(g.request.fields).sort()) === same)
55
- .filter((g) => !g.pending.expiresAt || g.pending.expiresAt > now)
58
+ .filter((g) => g.applied || !g.pending.expiresAt || g.pending.expiresAt > now)
56
59
  .at(-1);
57
60
  return standing?.request.at ?? now;
58
61
  }
@@ -70,6 +73,8 @@ export interface GatedOpInput {
70
73
  base?: string;
71
74
  /** A document the request carries, such as a migration's proof; its digest joins the request. */
72
75
  attachment?: string;
76
+ /** Reuse the `at` of a request with the same fields that applied already, so the call answers `spent` ({@link requestedAt}, #4808). */
77
+ reuseApplied?: boolean;
73
78
  cwd?: string;
74
79
  now?: string;
75
80
  runId?: string;
@@ -111,7 +116,7 @@ export async function gatedOp<T>(input: GatedOpInput, act: GatedOpAct<T>): Promi
111
116
  const ledger = input.ledger ?? chantGatedLedger;
112
117
  // The proof's digest is a field of the stored request, so the standing request is matched with it.
113
118
  const fields = input.attachment !== undefined ? { ...input.request.fields, proof: attachmentDigest(input.attachment) } : input.request.fields;
114
- const at = input.request.at ?? (await requestedAt(input.op, { ...input.request, fields }, { ...(input.now ? { now: input.now } : {}), ...(input.cwd ? { cwd: input.cwd } : {}), ledger }));
119
+ const at = input.request.at ?? (await requestedAt(input.op, { ...input.request, fields }, { ...(input.now ? { now: input.now } : {}), ...(input.cwd ? { cwd: input.cwd } : {}), ...(input.reuseApplied ? { reuseApplied: true } : {}), ledger }));
115
120
  const request: GatedRequest = { kind: input.request.kind, subject: input.request.subject, by: input.request.by, at, fields };
116
121
  const asked = await ledger.requestGate({
117
122
  op: input.op,
@@ -0,0 +1,94 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { fileURLToPath, pathToFileURL } from "node:url";
6
+ import { describe, expect, it } from "vitest";
7
+
8
+ /**
9
+ * #4787 end to end: `chant dev local <checkout>` through the real CLI, with
10
+ * real `npm pack` and `npm install`, on a fixture checkout and a fixture
11
+ * product. Nothing reaches a registry: every chant package comes from a
12
+ * tarball and the fixtures have no other dependencies.
13
+ */
14
+
15
+ const here = dirname(fileURLToPath(import.meta.url));
16
+ const mainTs = resolve(here, "cli/main.ts");
17
+ /**
18
+ * tsx's loader by path, under plain node: the fixtures sit outside the
19
+ * worktree, where npx would look tsx up again, and the tsx command's IPC
20
+ * socket in a long TMPDIR passes the socket path limit.
21
+ */
22
+ const tsxLoader = pathToFileURL(resolve(here, "../../../node_modules/tsx/dist/loader.mjs")).href;
23
+
24
+ const write = (file: string, body: string | object) => {
25
+ mkdirSync(dirname(file), { recursive: true });
26
+ writeFileSync(file, typeof body === "string" ? body : JSON.stringify(body, null, 2) + "\n");
27
+ };
28
+
29
+ /** A chant checkout whose core and k8s lexicon are already built (dist/ in place, no prepack). */
30
+ function checkout(): string {
31
+ const dir = mkdtempSync(join(tmpdir(), "chant-4787-e2e-checkout-"));
32
+ write(join(dir, "package.json"), { name: "chant-monorepo", private: true, workspaces: ["packages/*", "lexicons/*"] });
33
+ write(join(dir, "packages/core/package.json"), { name: "@intentius/chant", version: "2.0.0", type: "module", files: ["dist/"], exports: { ".": { import: "./dist/index.js" } } });
34
+ write(join(dir, "packages/core/dist/index.js"), "export const local = true;\n");
35
+ write(join(dir, "lexicons/k8s/package.json"), { name: "@intentius/chant-lexicon-k8s", version: "2.0.0", type: "module", files: ["dist/"], exports: { ".": { default: "./dist/index.js" } }, peerDependencies: { "@intentius/chant": "2.0.0" } });
36
+ write(join(dir, "lexicons/k8s/dist/index.js"), "export {};\n");
37
+ // A lock for the checkout's npm ci: workspaces only, so npm writes it offline.
38
+ const lock = spawnSync("npm", ["install", "--package-lock-only", "--offline", "--no-audit", "--no-fund"], { cwd: dir, encoding: "utf8" });
39
+ if (lock.status !== 0) throw new Error(`npm install --package-lock-only: ${lock.stderr}`);
40
+ return dir;
41
+ }
42
+
43
+ /** A product pinned to chant 2.0.0 whose `packages/app` bundle imports chant core. */
44
+ function product(): string {
45
+ const dir = mkdtempSync(join(tmpdir(), "chant-4787-e2e-product-"));
46
+ write(join(dir, "package.json"), { name: "product", private: true, workspaces: ["packages/*"], devDependencies: { "@intentius/chant": "2.0.0", "@intentius/chant-lexicon-k8s": "2.0.0" } });
47
+ write(join(dir, "packages/app/package.json"), {
48
+ name: "@example/app",
49
+ version: "0.1.0",
50
+ dependencies: { "@intentius/chant": "2.0.0" },
51
+ devDependencies: { "@intentius/chant-lexicon-k8s": "2.0.0" },
52
+ chantBundleCheck: { bundle: "dist/app.mjs", maxBytes: 4096 },
53
+ });
54
+ write(join(dir, "package-lock.json"), '{\n "name": "product",\n "lockfileVersion": 3,\n "requires": true,\n "packages": {}\n}\n');
55
+ return dir;
56
+ }
57
+
58
+ const chant = (cwd: string, ...args: string[]) =>
59
+ spawnSync(process.execPath, ["--import", tsxLoader, mainTs, ...args], { cwd, encoding: "utf8", env: { ...process.env, NO_COLOR: "1", npm_config_offline: "true" }, timeout: 110_000 });
60
+
61
+ describe("chant dev local (#4787)", () => {
62
+ it("packs a checkout into a product, keeps its manifests and lock, builds, and checks the bundle", () => {
63
+ const repo = checkout();
64
+ const dir = product();
65
+ const files = ["package.json", "packages/app/package.json", "package-lock.json"];
66
+ const before = files.map((f) => readFileSync(join(dir, f), "utf8"));
67
+ const build = "mkdir -p packages/app/dist && printf 'import { local } from \"@intentius/chant\";\\nconsole.log(local);\\n' > packages/app/dist/app.mjs";
68
+
69
+ const r = chant(dir, "dev", "local", repo, "--build", build);
70
+ expect(r.stderr).toContain("bundle-check: @example/app");
71
+ expect(r.status).toBe(0);
72
+ expect(r.stdout).toContain("chant commit:");
73
+ expect(files.map((f) => readFileSync(join(dir, f), "utf8"))).toEqual(before);
74
+
75
+ const core = JSON.parse(readFileSync(join(dir, "node_modules/@intentius/chant/package.json"), "utf8"));
76
+ expect(core.version).toBe("2.0.0");
77
+ expect(core.chantLocal.dir).toBe(repo);
78
+ const lexicon = JSON.parse(readFileSync(join(dir, "node_modules/@intentius/chant-lexicon-k8s/package.json"), "utf8"));
79
+ expect(lexicon.chantLocal).toBeDefined();
80
+
81
+ // The bundle check on its own, and one that fails: an import the installed chant does not serve.
82
+ expect(chant(dir, "dev", "bundle-check", "packages/app").status).toBe(0);
83
+ writeFileSync(join(dir, "packages/app/dist/app.mjs"), 'import "@intentius/chant/missing";\n');
84
+ const bad = chant(dir, "dev", "bundle-check");
85
+ expect(bad.status).toBe(1);
86
+ expect(bad.stderr).toContain("'@intentius/chant/missing', which the installed package's exports do not serve as compiled JS");
87
+ }, 120_000);
88
+
89
+ it("refuses a usage without a checkout", () => {
90
+ const r = chant(product(), "dev", "local");
91
+ expect(r.status).toBe(2);
92
+ expect(r.stderr).toContain("chant dev local needs a chant checkout");
93
+ }, 60_000);
94
+ });
@@ -0,0 +1,162 @@
1
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { basename, dirname, join } from "node:path";
4
+ import { describe, expect, it } from "vitest";
5
+ import { chantPackages, installLocalChant, LocalChantError, lockMismatches, packOrder, pointAtTarballs, productChantNames, productManifests, type Runner } from "./local-chant";
6
+
7
+ /** #4787: what terragucci's and plywood's scripts/chant-local.sh did, as chant's `chant dev local`. */
8
+
9
+ const write = (file: string, body: string | object) => {
10
+ mkdirSync(dirname(file), { recursive: true });
11
+ writeFileSync(file, typeof body === "string" ? body : JSON.stringify(body, null, 2) + "\n");
12
+ };
13
+
14
+ /** A chant checkout: core 2.0.0, a k8s lexicon on core, a fountain lexicon on k8s, and a private package. */
15
+ function checkout(): string {
16
+ const dir = mkdtempSync(join(tmpdir(), "chant-4787-checkout-"));
17
+ write(join(dir, "package.json"), { name: "chant-monorepo", private: true, workspaces: ["packages/*", "lexicons/*"] });
18
+ write(join(dir, "packages/core/package.json"), { name: "@intentius/chant", version: "2.0.0" });
19
+ write(join(dir, "packages/internal/package.json"), { name: "internal", private: true });
20
+ write(join(dir, "lexicons/k8s/package.json"), { name: "@intentius/chant-lexicon-k8s", version: "2.0.0", peerDependencies: { "@intentius/chant": "2.0.0" } });
21
+ write(join(dir, "lexicons/fountain/package.json"), { name: "@intentius/chant-lexicon-fountain", version: "2.0.0", dependencies: { "@intentius/chant-lexicon-k8s": "2.0.0", yaml: "^2" } });
22
+ return dir;
23
+ }
24
+
25
+ /** A product pinned to chant 1.0.0, at the root and in `packages/app`. */
26
+ function product(): string {
27
+ const dir = mkdtempSync(join(tmpdir(), "chant-4787-product-"));
28
+ write(join(dir, "package.json"), { name: "product", private: true, workspaces: ["packages/*"], devDependencies: { "@intentius/chant": "1.0.0", "@intentius/chant-lexicon-k8s": "1.0.0" } });
29
+ write(join(dir, "packages/app/package.json"), { name: "@example/app", dependencies: { "@intentius/chant": "1.0.0" }, devDependencies: { esbuild: "^0.25.0" } });
30
+ write(join(dir, "packages/notes.txt"), "not a package\n");
31
+ write(join(dir, "package-lock.json"), '{\n "name": "product",\n "lockfileVersion": 3,\n "packages": {}\n}\n');
32
+ return dir;
33
+ }
34
+
35
+ describe("the packages to pack (#4787)", () => {
36
+ it("lists a checkout's public packages and orders them after what they depend on", () => {
37
+ const pkgs = chantPackages(checkout());
38
+ expect([...pkgs.keys()].sort()).toEqual(["@intentius/chant", "@intentius/chant-lexicon-fountain", "@intentius/chant-lexicon-k8s"]);
39
+ expect(packOrder(pkgs, ["@intentius/chant-lexicon-fountain"]).map((p) => p.dir)).toEqual(["packages/core", "lexicons/k8s", "lexicons/fountain"]);
40
+ expect(packOrder(pkgs, ["@intentius/chant"]).map((p) => p.name)).toEqual(["@intentius/chant"]);
41
+ });
42
+
43
+ it("refuses a package the checkout lacks, and a cycle", () => {
44
+ const pkgs = chantPackages(checkout());
45
+ expect(() => packOrder(pkgs, ["@intentius/chant-lexicon-nope"])).toThrow("the chant checkout has no package @intentius/chant-lexicon-nope");
46
+ pkgs.get("@intentius/chant")!.deps.push("@intentius/chant-lexicon-k8s");
47
+ expect(() => packOrder(pkgs, ["@intentius/chant"])).toThrow(LocalChantError);
48
+ });
49
+
50
+ it("reads the product's manifests and the chant packages they name", () => {
51
+ const dir = product();
52
+ expect(productManifests(dir)).toEqual(["package.json", "packages/app/package.json"]);
53
+ expect(productChantNames(dir)).toEqual(["@intentius/chant", "@intentius/chant-lexicon-k8s"]);
54
+ });
55
+
56
+ it("points a manifest at the tarballs, and the root at every one", () => {
57
+ const local = new Map([["@intentius/chant", "file:/t/a.tgz"], ["@intentius/chant-lexicon-k8s", "file:/t/b.tgz"]]);
58
+ const app = pointAtTarballs({ dependencies: { "@intentius/chant": "1.0.0", other: "1" } }, local, false);
59
+ expect(app).toEqual({ dependencies: { "@intentius/chant": "file:/t/a.tgz", other: "1" } });
60
+ const root = pointAtTarballs({ dependencies: { "@intentius/chant": "1.0.0" } }, local, true);
61
+ expect(root).toEqual({ dependencies: { "@intentius/chant": "file:/t/a.tgz" }, devDependencies: { "@intentius/chant-lexicon-k8s": "file:/t/b.tgz" } });
62
+ });
63
+ });
64
+
65
+ /** A runner standing in for npm: pack writes a versioned tarball; install copies each `file:` dependency the manifests name into node_modules. */
66
+ function fakeNpm(seen: { manifests?: string[]; calls: string[] }, opts: { installVersion?: string } = {}): Runner {
67
+ return (command, args, cwd) => {
68
+ seen.calls.push(`${command} ${args[0]} ${basename(cwd)}`);
69
+ if (args[0] === "pack") {
70
+ const p = JSON.parse(readFileSync(join(cwd, "package.json"), "utf8"));
71
+ const file = `${p.name.replace(/^@/, "").replace("/", "-")}-${p.version}.tgz`;
72
+ writeFileSync(join(args[args.indexOf("--pack-destination") + 1], file), "tgz");
73
+ return `${file}\n`;
74
+ }
75
+ if (args[0] === "install") {
76
+ seen.manifests = productManifests(cwd).map((f) => readFileSync(join(cwd, f), "utf8"));
77
+ for (const f of productManifests(cwd)) {
78
+ const p = JSON.parse(readFileSync(join(cwd, f), "utf8"));
79
+ for (const [name, spec] of Object.entries({ ...p.dependencies, ...p.devDependencies } as Record<string, string>)) {
80
+ if (!spec.startsWith("file:")) continue;
81
+ const at = join(cwd, f === "package.json" ? "" : dirname(f), "node_modules", name);
82
+ write(join(at, "package.json"), { name, version: opts.installVersion ?? "2.0.0" });
83
+ }
84
+ }
85
+ // npm writes the lock unless --no-save; the restore must undo it either way.
86
+ writeFileSync(join(cwd, "package-lock.json"), "changed\n");
87
+ return "";
88
+ }
89
+ return "";
90
+ };
91
+ }
92
+
93
+ describe("installLocalChant (#4787)", () => {
94
+ it("packs, installs with --no-save, puts the manifests and lock back byte for byte, and marks each copy", () => {
95
+ const chant = checkout();
96
+ const dir = product();
97
+ const before = ["package.json", "packages/app/package.json", "package-lock.json"].map((f) => readFileSync(join(dir, f), "utf8"));
98
+ const seen: { manifests?: string[]; calls: string[] } = { calls: [] };
99
+ const r = installLocalChant({ productDir: dir, chantDir: chant, install: false, run: fakeNpm(seen), log: () => {} });
100
+
101
+ expect(r.packed.map((p) => p.dir)).toEqual(["packages/core", "lexicons/k8s"]);
102
+ expect(seen.calls).toEqual(["npm pack core", "npm pack k8s", `npm install ${basename(dir)}`]);
103
+ expect(existsSync(join(dir, ".chant-local/intentius-chant.tgz"))).toBe(true);
104
+ expect(existsSync(join(dir, ".chant-local/intentius-chant-2.0.0.tgz"))).toBe(false);
105
+ // During the install every manifest named the tarballs.
106
+ expect(seen.manifests![0]).toContain(`"@intentius/chant": "file:${join(dir, ".chant-local/intentius-chant.tgz")}"`);
107
+ expect(seen.manifests![1]).toContain(`"@intentius/chant": "file:${join(dir, ".chant-local/intentius-chant.tgz")}"`);
108
+ expect(["package.json", "packages/app/package.json", "package-lock.json"].map((f) => readFileSync(join(dir, f), "utf8"))).toEqual(before);
109
+
110
+ expect(r.marked).toBe(3);
111
+ const core = JSON.parse(readFileSync(join(dir, "packages/app/node_modules/@intentius/chant/package.json"), "utf8"));
112
+ expect(core.chantLocal).toEqual({ commit: r.mark.commit, dir: chant });
113
+ expect(JSON.parse(readFileSync(join(dir, ".chant-local/packages.json"), "utf8")).map((p: { name: string }) => p.name)).toEqual(["@intentius/chant", "@intentius/chant-lexicon-k8s"]);
114
+ });
115
+
116
+ it("packs a --with package and its chant dependencies", () => {
117
+ const seen = { calls: [] as string[] };
118
+ const r = installLocalChant({ productDir: product(), chantDir: checkout(), with: ["@intentius/chant-lexicon-fountain"], install: false, run: fakeNpm(seen), log: () => {} });
119
+ expect(r.packed.map((p) => p.name)).toEqual(["@intentius/chant", "@intentius/chant-lexicon-k8s", "@intentius/chant-lexicon-fountain"]);
120
+ });
121
+
122
+ it("puts the manifests back when the install fails", () => {
123
+ const dir = product();
124
+ const before = readFileSync(join(dir, "package.json"), "utf8");
125
+ const npm = fakeNpm({ calls: [] });
126
+ const failing: Runner = (c, a, cwd) => {
127
+ if (a[0] === "install") throw new LocalChantError("npm install exited 1");
128
+ return npm(c, a, cwd);
129
+ };
130
+ expect(() => installLocalChant({ productDir: dir, chantDir: checkout(), install: false, run: failing, log: () => {} })).toThrow("npm install exited 1");
131
+ expect(readFileSync(join(dir, "package.json"), "utf8")).toBe(before);
132
+ });
133
+
134
+ it("fails when an installed copy is not the checkout's version", () => {
135
+ const run = fakeNpm({ calls: [] }, { installVersion: "1.0.0" });
136
+ expect(() => installLocalChant({ productDir: product(), chantDir: checkout(), install: false, run, log: () => {} })).toThrow(/is 1\.0\.0, the checkout's is 2\.0\.0/);
137
+ });
138
+
139
+ it("runs npm ci in the checkout only when its lock changed", () => {
140
+ const chant = checkout();
141
+ write(join(chant, "package-lock.json"), "{}\n");
142
+ mkdirSync(join(chant, "node_modules"), { recursive: true });
143
+ const seen = { calls: [] as string[] };
144
+ installLocalChant({ productDir: product(), chantDir: chant, run: fakeNpm(seen), log: () => {} });
145
+ installLocalChant({ productDir: product(), chantDir: chant, run: fakeNpm(seen), log: () => {} });
146
+ expect(seen.calls.filter((c) => c.startsWith("npm ci"))).toHaveLength(1);
147
+ });
148
+
149
+ it("refuses a directory that is not a chant checkout", () => {
150
+ expect(() => installLocalChant({ productDir: product(), chantDir: tmpdir(), install: false, log: () => {} })).toThrow("is not a chant checkout");
151
+ });
152
+ });
153
+
154
+ describe("lockMismatches (#4787)", () => {
155
+ it("names a copy off the lock and a local build", () => {
156
+ const dir = mkdtempSync(join(tmpdir(), "chant-4787-reset-"));
157
+ write(join(dir, "package-lock.json"), { packages: { "node_modules/@intentius/chant": { version: "1.0.0" }, "node_modules/@intentius/chant-lexicon-k8s": { version: "1.0.0" }, "node_modules/left-pad": { version: "1.0.0" } } });
158
+ write(join(dir, "node_modules/@intentius/chant/package.json"), { version: "1.0.0" });
159
+ write(join(dir, "node_modules/@intentius/chant-lexicon-k8s/package.json"), { version: "1.0.0", chantLocal: { commit: "abc", dir: "/c" } });
160
+ expect(lockMismatches(dir)).toEqual(["node_modules/@intentius/chant-lexicon-k8s is 1.0.0 (local build), the lock says 1.0.0"]);
161
+ });
162
+ });