@jfalava/ts-standard 0.0.0-stage → 0.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.
@@ -0,0 +1,279 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ import type { Finding } from "./finding.ts";
5
+ import type { Repo } from "./repo.ts";
6
+ import { asBunRun, parseScript } from "./shell.ts";
7
+
8
+ /** The shared `ci.yml`, copied from lazyotp. */
9
+ const REFERENCE = join(import.meta.dir, "..", "reference", "ci.yml");
10
+ const PINNED = /^\s*(?:-\s+)?uses:\s*([^@\s]+)@([0-9a-f]{40})\s+#\s*v\d/;
11
+ const USES = /^\s*(?:-\s+)?uses:\s*(\S+)/;
12
+
13
+ const stripRef = (v: any): any => {
14
+ if (Array.isArray(v)) return v.map(stripRef);
15
+ if (v && typeof v === "object") {
16
+ return Object.fromEntries(
17
+ Object.entries(v).map(([k, x]) => [
18
+ k,
19
+ k === "uses" && typeof x === "string" ? x.replace(/@.*$/, "") : stripRef(x),
20
+ ]),
21
+ );
22
+ }
23
+ return v;
24
+ };
25
+
26
+ const diffPaths = (a: any, b: any, path = ""): string[] => {
27
+ if (JSON.stringify(a) === JSON.stringify(b)) return [];
28
+ if (
29
+ a &&
30
+ b &&
31
+ typeof a === "object" &&
32
+ typeof b === "object" &&
33
+ Array.isArray(a) === Array.isArray(b)
34
+ ) {
35
+ const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
36
+ return [...keys].flatMap((k) => diffPaths(a[k], b[k], path ? `${path}.${k}` : k));
37
+ }
38
+ return [`${path || "<root>"}: expected ${JSON.stringify(a)}, got ${JSON.stringify(b)}`];
39
+ };
40
+
41
+ /** Removes the repo's declared additions so what remains must equal the reference. */
42
+ const normalizeCi = (ci: any, repo: Repo): any => {
43
+ const c = structuredClone(ci);
44
+ const extra = repo.config.ci ?? {};
45
+ for (const k of extra.env ?? []) delete c.env?.[k];
46
+ if (c.env && Object.keys(c.env).length === 0) delete c.env;
47
+ for (const j of extra.jobs ?? []) delete c.jobs?.[j];
48
+ const changes = c.jobs?.changes;
49
+ for (const k of extra.filters ?? []) delete changes?.outputs?.[k];
50
+ const step = changes?.steps?.find(
51
+ (s: any) => typeof s.uses === "string" && s.uses.startsWith("dorny/paths-filter"),
52
+ );
53
+ if (step?.with?.filters) {
54
+ const filters: any = Bun.YAML.parse(step.with.filters);
55
+ for (const k of extra.filters ?? []) delete filters[k];
56
+ if (Array.isArray(filters.code)) {
57
+ const added = new Set((extra.ignoreAdd ?? []).map((p) => `!${p}`));
58
+ const code = filters.code.filter((p: string) => !added.has(p));
59
+ const removed = (extra.ignoreRemove ?? []).map((p) => `!${p}`);
60
+ filters.code = [...code, ...removed];
61
+ }
62
+ step.with.filters = filters;
63
+ }
64
+ return c;
65
+ };
66
+
67
+ const referenceCi = (): any => {
68
+ const ref: any = Bun.YAML.parse(readFileSync(REFERENCE, "utf8"));
69
+ const step = ref.jobs.changes.steps.find((s: any) => s.uses?.startsWith("dorny/paths-filter"));
70
+ step.with.filters = Bun.YAML.parse(step.with.filters);
71
+ return ref;
72
+ };
73
+
74
+ /** Takes the `code` filter's patterns out of a parsed ci.yml, so they can be compared as a set. */
75
+ const takeCode = (ci: any): string[] => {
76
+ const step = ci.jobs?.changes?.steps?.find((s: any) =>
77
+ s.uses?.startsWith?.("dorny/paths-filter"),
78
+ );
79
+ const code = step?.with?.filters?.code;
80
+ if (!Array.isArray(code)) return [];
81
+ delete step.with.filters.code;
82
+ return code;
83
+ };
84
+
85
+ const runLines = (wf: any): { job: string; line: string }[] =>
86
+ Object.entries<any>(wf.jobs ?? {}).flatMap(([job, j]) =>
87
+ (j.steps ?? []).flatMap((s: any) =>
88
+ typeof s.run === "string"
89
+ ? s.run.split("\n").map((line: string) => ({ job, line: line.trim() }))
90
+ : [],
91
+ ),
92
+ );
93
+
94
+ export const workflowRules = (repo: Repo): Finding[] => {
95
+ const out: Finding[] = [];
96
+ const f = (rule: string, where: string, message: string) => out.push({ rule, where, message });
97
+ const dir = join(repo.root, ".github", "workflows");
98
+ const files = existsSync(dir) ? readdirSync(dir).filter((n) => /\.ya?ml$/.test(n)) : [];
99
+ const visibility = repo.config.visibility ?? "public";
100
+
101
+ if (visibility === "public" && !files.includes("ci.yml"))
102
+ f(
103
+ "workflows/ci-reference",
104
+ ".github/workflows/ci.yml",
105
+ "public repos gate on `ci.yml`; it is missing",
106
+ );
107
+ if (visibility === "private" && files.includes("ci.yml"))
108
+ f(
109
+ "workflows/ci-reference",
110
+ ".github/workflows/ci.yml",
111
+ "private repos gate on Workers Builds, not `ci.yml`",
112
+ );
113
+
114
+ const depPath = join(repo.root, ".github", "dependabot.yml");
115
+ const dep: any = existsSync(depPath) ? Bun.YAML.parse(readFileSync(depPath, "utf8")) : undefined;
116
+ if (
117
+ files.length > 0 &&
118
+ !dep?.updates?.some((u: any) => u["package-ecosystem"] === "github-actions")
119
+ ) {
120
+ f(
121
+ "workflows/dependabot",
122
+ ".github/dependabot.yml",
123
+ "no `github-actions` update entry, so the SHA pins never move",
124
+ );
125
+ }
126
+
127
+ const ref = referenceCi();
128
+ const refPins = new Map<string, string>();
129
+ for (const line of readFileSync(REFERENCE, "utf8").split("\n")) {
130
+ const m = PINNED.exec(line);
131
+ if (m) refPins.set(m[1]!, m[2]!);
132
+ }
133
+
134
+ for (const name of files) {
135
+ const where = `.github/workflows/${name}`;
136
+ const text = readFileSync(join(dir, name), "utf8");
137
+ const wf: any = Bun.YAML.parse(text);
138
+
139
+ // Pins are read from the text: the version comment is not in the parsed YAML.
140
+ text.split("\n").forEach((line, i) => {
141
+ const u = USES.exec(line);
142
+ if (!u || u[1]!.startsWith("./")) return;
143
+ const p = PINNED.exec(line);
144
+ if (!p)
145
+ f(
146
+ "workflows/actions-pinned",
147
+ `${where}:${i + 1}`,
148
+ `\`${u[1]}\` is not pinned to a commit SHA with a \`# v…\` comment`,
149
+ );
150
+ else if (refPins.has(p[1]!) && refPins.get(p[1]!) !== p[2])
151
+ f(
152
+ "workflows/reference-pins",
153
+ `${where}:${i + 1}`,
154
+ `\`${p[1]}\` is at ${p[2]!.slice(0, 7)}, the reference at ${refPins.get(p[1]!)!.slice(0, 7)}`,
155
+ );
156
+ });
157
+
158
+ if (wf.permissions === undefined) f("workflows/hygiene", where, "no top-level `permissions`");
159
+ if (wf.concurrency === undefined && wf.on?.workflow_call === undefined)
160
+ f("workflows/hygiene", where, "no `concurrency` group");
161
+ for (const [job, j] of Object.entries<any>(wf.jobs ?? {})) {
162
+ if (j.uses === undefined && j["timeout-minutes"] === undefined)
163
+ f("workflows/hygiene", where, `job \`${job}\` has no \`timeout-minutes\``);
164
+ for (const s of j.steps ?? []) {
165
+ if (
166
+ typeof s.uses === "string" &&
167
+ s.uses.startsWith("oven-sh/setup-bun") &&
168
+ s.with?.["bun-version"] !== undefined
169
+ ) {
170
+ f(
171
+ "workflows/bun-from-package-manager",
172
+ where,
173
+ `job \`${job}\` sets \`bun-version\`; setup-bun reads \`packageManager\``,
174
+ );
175
+ }
176
+ }
177
+ }
178
+ for (const { job, line } of runLines(wf)) {
179
+ for (const cmd of parseScript(line)) {
180
+ const [bin, sub] = cmd.argv;
181
+ if (bin === "bunx" || (bin === "bun" && sub === "x"))
182
+ f("workflows/scripts-only", where, `job \`${job}\`: \`${cmd.raw}\`; call a script`);
183
+ else if (bin === "bun" && sub === "install" && !cmd.argv.includes("--frozen-lockfile"))
184
+ f(
185
+ "workflows/scripts-only",
186
+ where,
187
+ `job \`${job}\`: \`${cmd.raw}\` without \`--frozen-lockfile\``,
188
+ );
189
+ else if (bin === "bun" && sub !== "install" && !asBunRun(cmd))
190
+ f(
191
+ "workflows/scripts-only",
192
+ where,
193
+ `job \`${job}\`: \`${cmd.raw}\` is inline; make it a script`,
194
+ );
195
+ if (
196
+ bin === "bun" &&
197
+ (sub === "install" || sub === "i") &&
198
+ cmd.argv.includes("--ignore-scripts")
199
+ ) {
200
+ f(
201
+ "workflows/scripts-only",
202
+ where,
203
+ `job \`${job}\`: \`--ignore-scripts\` skips the Effect patch`,
204
+ );
205
+ }
206
+ }
207
+ }
208
+
209
+ if (name === "ci.yml") {
210
+ const got = stripRef(normalizeCi(wf, repo));
211
+ const want = stripRef(structuredClone(ref));
212
+ const gotCode = new Set(takeCode(got));
213
+ const wantCode = takeCode(want);
214
+ for (const p of wantCode.filter((x) => !gotCode.has(x)))
215
+ f(
216
+ "workflows/ci-reference",
217
+ where,
218
+ `the \`code\` filter lacks "${p}"; declare it in \`ci.ignoreRemove\` if intended`,
219
+ );
220
+ for (const p of [...gotCode].filter((x) => !wantCode.includes(x)))
221
+ f(
222
+ "workflows/ci-reference",
223
+ where,
224
+ `the \`code\` filter has "${p}"; declare it in \`ci.ignoreAdd\` if intended`,
225
+ );
226
+ for (const d of diffPaths(want, got)) f("workflows/ci-reference", where, d);
227
+ }
228
+
229
+ const tags = wf.on?.push?.tags;
230
+ if (tags !== undefined) out.push(...releaseRules(repo, where, wf));
231
+ }
232
+ return out;
233
+ };
234
+
235
+ const releaseRules = (repo: Repo, where: string, wf: any): Finding[] => {
236
+ const out: Finding[] = [];
237
+ const lines = runLines(wf);
238
+ const runs = lines.flatMap(({ job, line }) =>
239
+ parseScript(line).map((cmd) => ({ job, cmd, run: asBunRun(cmd) })),
240
+ );
241
+ if (!runs.some((r) => r.run?.script === "check"))
242
+ out.push({
243
+ rule: "workflows/release-check",
244
+ where,
245
+ message: "no job runs `bun run check` before releasing",
246
+ });
247
+ if (!lines.some(({ line }) => line.includes("GITHUB_REF_NAME#v")))
248
+ out.push({
249
+ rule: "workflows/release-version",
250
+ where,
251
+ message: "no step checks the tag against the package version",
252
+ });
253
+ const builds = runs.filter((r) => r.run?.script.startsWith("build:"));
254
+ if (builds.length === 0)
255
+ out.push({
256
+ rule: "workflows/release-build",
257
+ where,
258
+ message: "no step calls a `build:<target>` script",
259
+ });
260
+ for (const b of builds) {
261
+ const pkg = repo.pkgAt(b.run!.cwd ?? ".");
262
+ const job = wf.jobs[b.job];
263
+ const targets: string[] = (job?.strategy?.matrix?.include ?? [])
264
+ .map((m: any) => m.target)
265
+ .filter(Boolean);
266
+ const names = b.run!.script.includes("${{ matrix.target }}")
267
+ ? targets.map((t) => b.run!.script.replace("${{ matrix.target }}", t))
268
+ : [b.run!.script];
269
+ for (const n of names) {
270
+ if (pkg?.scripts[n] === undefined)
271
+ out.push({
272
+ rule: "workflows/release-build",
273
+ where,
274
+ message: `calls \`${n}\`, which ${pkg?.dir ?? b.run!.cwd} does not define`,
275
+ });
276
+ }
277
+ }
278
+ return out;
279
+ };