@jfalava/ts-standard 0.0.0-stage → 0.2.2

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.
package/src/shell.ts ADDED
@@ -0,0 +1,165 @@
1
+ // Just enough shell parsing for package.json script bodies: split on && || ; |,
2
+ // honour quotes, and peel leading VAR=value assignments.
3
+
4
+ export interface Command {
5
+ readonly env: ReadonlyMap<string, string>;
6
+ readonly argv: readonly string[];
7
+ readonly raw: string;
8
+ }
9
+
10
+ const tokenize = (body: string): string[][] => {
11
+ const commands: string[][] = [];
12
+ let current: string[] = [];
13
+ let token = "";
14
+ let hasToken = false;
15
+ let quote: "'" | '"' | null = null;
16
+ const pushToken = () => {
17
+ if (hasToken) {
18
+ current.push(token);
19
+ }
20
+ token = "";
21
+ hasToken = false;
22
+ };
23
+ const pushCommand = () => {
24
+ pushToken();
25
+ if (current.length > 0) {
26
+ commands.push(current);
27
+ }
28
+ current = [];
29
+ };
30
+ for (let i = 0; i < body.length; i++) {
31
+ const c = body[i]!;
32
+ if (quote) {
33
+ if (c === quote) {
34
+ quote = null;
35
+ } else {
36
+ token += c;
37
+ }
38
+ continue;
39
+ }
40
+ // GitHub expressions such as `${{ matrix.target }}` are one word.
41
+ if (c === "$" && body.startsWith("${{", i)) {
42
+ const end = body.indexOf("}}", i);
43
+ const stop = end < 0 ? body.length : end + 2;
44
+ token += body.slice(i, stop);
45
+ hasToken = true;
46
+ i = stop - 1;
47
+ continue;
48
+ }
49
+ if (c === "'" || c === '"') {
50
+ quote = c;
51
+ hasToken = true;
52
+ continue;
53
+ }
54
+ if (c === "&" && body[i + 1] === "&") {
55
+ pushCommand();
56
+ i++;
57
+ continue;
58
+ }
59
+ if (c === "|" || c === ";") {
60
+ pushCommand();
61
+ if (body[i + 1] === "|") {
62
+ i++;
63
+ }
64
+ continue;
65
+ }
66
+ if (c === " " || c === "\t" || c === "\n") {
67
+ pushToken();
68
+ continue;
69
+ }
70
+ token += c;
71
+ hasToken = true;
72
+ }
73
+ pushCommand();
74
+ return commands;
75
+ };
76
+
77
+ export const parseScript = (body: string): Command[] =>
78
+ tokenize(body).map((tokens) => {
79
+ const env = new Map<string, string>();
80
+ let i = 0;
81
+ for (; i < tokens.length; i++) {
82
+ const m = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s.exec(tokens[i]!);
83
+ if (!m) {
84
+ break;
85
+ }
86
+ env.set(m[1]!, m[2]!);
87
+ }
88
+ const argv = tokens.slice(i);
89
+ return { env, argv, raw: tokens.join(" ") };
90
+ });
91
+
92
+ export interface BunRun {
93
+ readonly workspaces: boolean;
94
+ readonly ifPresent: boolean;
95
+ readonly cwd: string | undefined;
96
+ readonly filter: string | undefined;
97
+ readonly script: string;
98
+ readonly args: readonly string[];
99
+ }
100
+
101
+ /** `bun run [flags] <script> [args]`, or undefined for anything else (including `bun run file.ts`). */
102
+ export const asBunRun = (cmd: Command): BunRun | undefined => {
103
+ const [bin, sub, ...rest] = cmd.argv;
104
+ if (bin !== "bun" || sub !== "run") {
105
+ return undefined;
106
+ }
107
+ let workspaces = false;
108
+ let ifPresent = false;
109
+ let cwd: string | undefined;
110
+ let filter: string | undefined;
111
+ let i = 0;
112
+ for (; i < rest.length; i++) {
113
+ const a = rest[i]!;
114
+ if (a === "--workspaces") {
115
+ workspaces = true;
116
+ } else if (a === "--if-present") {
117
+ ifPresent = true;
118
+ } else if (a === "--sequential" || a === "--silent" || a === "--bun") {
119
+ continue;
120
+ } else if (a === "--cwd") {
121
+ cwd = rest[++i];
122
+ } else if (a.startsWith("--cwd=")) {
123
+ cwd = a.slice(6);
124
+ } else if (a === "--filter" || a === "-F") {
125
+ filter = rest[++i];
126
+ } else if (a.startsWith("--filter=")) {
127
+ filter = a.slice(9);
128
+ } else {
129
+ break;
130
+ }
131
+ }
132
+ const script = rest[i];
133
+ if (script === undefined || /\.(m?[jt]s|tsx?)$/.test(script)) {
134
+ return undefined;
135
+ }
136
+ return { workspaces, ifPresent, cwd, filter, script, args: rest.slice(i + 1) };
137
+ };
138
+
139
+ /** Commands that rewrite tracked files. */
140
+ export const isWriter = (argv: readonly string[]): boolean => {
141
+ const [bin, sub] = argv;
142
+ const has = (flag: string) => argv.includes(flag);
143
+ if (has("--fix") || has("--write") || has("-w")) {
144
+ return true;
145
+ }
146
+ if (bin === "oxfmt") {
147
+ return !has("--check") && !has("--list-different");
148
+ }
149
+ if (bin === "vp" && sub === "fmt") {
150
+ return !has("--check");
151
+ }
152
+ if (bin === "cargo" && sub === "fmt") {
153
+ return !has("--check");
154
+ }
155
+ if (bin === "biome" && (sub === "format" || sub === "check")) {
156
+ return has("--write");
157
+ }
158
+ return false;
159
+ };
160
+
161
+ export const isBareBunTest = (argv: readonly string[]): boolean =>
162
+ argv[0] === "bun" && argv[1] === "test";
163
+
164
+ export const isBunx = (argv: readonly string[]): boolean =>
165
+ argv[0] === "bunx" || (argv[0] === "bun" && argv[1] === "x");
@@ -0,0 +1,317 @@
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)) {
15
+ return v.map(stripRef);
16
+ }
17
+ if (v && typeof v === "object") {
18
+ return Object.fromEntries(
19
+ Object.entries(v).map(([k, x]) => [
20
+ k,
21
+ k === "uses" && typeof x === "string" ? x.replace(/@.*$/, "") : stripRef(x),
22
+ ]),
23
+ );
24
+ }
25
+ return v;
26
+ };
27
+
28
+ const diffPaths = (a: any, b: any, path = ""): string[] => {
29
+ if (JSON.stringify(a) === JSON.stringify(b)) {
30
+ return [];
31
+ }
32
+ if (
33
+ a &&
34
+ b &&
35
+ typeof a === "object" &&
36
+ typeof b === "object" &&
37
+ Array.isArray(a) === Array.isArray(b)
38
+ ) {
39
+ const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
40
+ return [...keys].flatMap((k) => diffPaths(a[k], b[k], path ? `${path}.${k}` : k));
41
+ }
42
+ return [`${path || "<root>"}: expected ${JSON.stringify(a)}, got ${JSON.stringify(b)}`];
43
+ };
44
+
45
+ /** Removes the repo's declared additions so what remains must equal the reference. */
46
+ const normalizeCi = (ci: any, repo: Repo): any => {
47
+ const c = structuredClone(ci);
48
+ const extra = repo.config.ci ?? {};
49
+ for (const k of extra.env ?? []) {
50
+ delete c.env?.[k];
51
+ }
52
+ if (c.env && Object.keys(c.env).length === 0) {
53
+ delete c.env;
54
+ }
55
+ for (const j of extra.jobs ?? []) {
56
+ delete c.jobs?.[j];
57
+ }
58
+ const changes = c.jobs?.changes;
59
+ for (const k of extra.filters ?? []) {
60
+ delete changes?.outputs?.[k];
61
+ }
62
+ const step = changes?.steps?.find(
63
+ (s: any) => typeof s.uses === "string" && s.uses.startsWith("dorny/paths-filter"),
64
+ );
65
+ if (step?.with?.filters) {
66
+ const filters: any = Bun.YAML.parse(step.with.filters);
67
+ for (const k of extra.filters ?? []) {
68
+ delete filters[k];
69
+ }
70
+ if (Array.isArray(filters.code)) {
71
+ const added = new Set((extra.ignoreAdd ?? []).map((p) => `!${p}`));
72
+ const code = filters.code.filter((p: string) => !added.has(p));
73
+ const removed = (extra.ignoreRemove ?? []).map((p) => `!${p}`);
74
+ filters.code = [...code, ...removed];
75
+ }
76
+ step.with.filters = filters;
77
+ }
78
+ return c;
79
+ };
80
+
81
+ const referenceCi = (): any => {
82
+ const ref: any = Bun.YAML.parse(readFileSync(REFERENCE, "utf8"));
83
+ const step = ref.jobs.changes.steps.find((s: any) => s.uses?.startsWith("dorny/paths-filter"));
84
+ step.with.filters = Bun.YAML.parse(step.with.filters);
85
+ return ref;
86
+ };
87
+
88
+ /** Takes the `code` filter's patterns out of a parsed ci.yml, so they can be compared as a set. */
89
+ const takeCode = (ci: any): string[] => {
90
+ const step = ci.jobs?.changes?.steps?.find((s: any) =>
91
+ s.uses?.startsWith?.("dorny/paths-filter"),
92
+ );
93
+ const code = step?.with?.filters?.code;
94
+ if (!Array.isArray(code)) {
95
+ return [];
96
+ }
97
+ delete step.with.filters.code;
98
+ return code;
99
+ };
100
+
101
+ const runLines = (wf: any): { job: string; line: string }[] =>
102
+ Object.entries<any>(wf.jobs ?? {}).flatMap(([job, j]) =>
103
+ (j.steps ?? []).flatMap((s: any) =>
104
+ typeof s.run === "string"
105
+ ? s.run.split("\n").map((line: string) => ({ job, line: line.trim() }))
106
+ : [],
107
+ ),
108
+ );
109
+
110
+ export const workflowRules = (repo: Repo): Finding[] => {
111
+ const out: Finding[] = [];
112
+ const f = (rule: string, where: string, message: string) => out.push({ rule, where, message });
113
+ const dir = join(repo.root, ".github", "workflows");
114
+ const files = existsSync(dir) ? readdirSync(dir).filter((n) => /\.ya?ml$/.test(n)) : [];
115
+ const visibility = repo.config.visibility ?? "public";
116
+
117
+ if (visibility === "public" && !files.includes("ci.yml")) {
118
+ f(
119
+ "workflows/ci-reference",
120
+ ".github/workflows/ci.yml",
121
+ "public repos gate on `ci.yml`; it is missing",
122
+ );
123
+ }
124
+ if (visibility === "private" && files.includes("ci.yml")) {
125
+ f(
126
+ "workflows/ci-reference",
127
+ ".github/workflows/ci.yml",
128
+ "private repos gate on Workers Builds, not `ci.yml`",
129
+ );
130
+ }
131
+
132
+ const depPath = join(repo.root, ".github", "dependabot.yml");
133
+ const dep: any = existsSync(depPath) ? Bun.YAML.parse(readFileSync(depPath, "utf8")) : undefined;
134
+ if (
135
+ files.length > 0 &&
136
+ !dep?.updates?.some((u: any) => u["package-ecosystem"] === "github-actions")
137
+ ) {
138
+ f(
139
+ "workflows/dependabot",
140
+ ".github/dependabot.yml",
141
+ "no `github-actions` update entry, so the SHA pins never move",
142
+ );
143
+ }
144
+
145
+ const ref = referenceCi();
146
+ const refPins = new Map<string, string>();
147
+ for (const line of readFileSync(REFERENCE, "utf8").split("\n")) {
148
+ const m = PINNED.exec(line);
149
+ if (m) {
150
+ refPins.set(m[1]!, m[2]!);
151
+ }
152
+ }
153
+
154
+ for (const name of files) {
155
+ const where = `.github/workflows/${name}`;
156
+ const text = readFileSync(join(dir, name), "utf8");
157
+ const wf: any = Bun.YAML.parse(text);
158
+
159
+ // Pins are read from the text: the version comment is not in the parsed YAML.
160
+ text.split("\n").forEach((line, i) => {
161
+ const u = USES.exec(line);
162
+ if (!u || u[1]!.startsWith("./")) {
163
+ return;
164
+ }
165
+ const p = PINNED.exec(line);
166
+ if (!p) {
167
+ f(
168
+ "workflows/actions-pinned",
169
+ `${where}:${i + 1}`,
170
+ `\`${u[1]}\` is not pinned to a commit SHA with a \`# v…\` comment`,
171
+ );
172
+ } else if (refPins.has(p[1]!) && refPins.get(p[1]!) !== p[2]) {
173
+ f(
174
+ "workflows/reference-pins",
175
+ `${where}:${i + 1}`,
176
+ `\`${p[1]}\` is at ${p[2]!.slice(0, 7)}, the reference at ${refPins.get(p[1]!)!.slice(0, 7)}`,
177
+ );
178
+ }
179
+ });
180
+
181
+ if (wf.permissions === undefined) {
182
+ f("workflows/hygiene", where, "no top-level `permissions`");
183
+ }
184
+ if (wf.concurrency === undefined && wf.on?.workflow_call === undefined) {
185
+ f("workflows/hygiene", where, "no `concurrency` group");
186
+ }
187
+ for (const [job, j] of Object.entries<any>(wf.jobs ?? {})) {
188
+ if (j.uses === undefined && j["timeout-minutes"] === undefined) {
189
+ f("workflows/hygiene", where, `job \`${job}\` has no \`timeout-minutes\``);
190
+ }
191
+ for (const s of j.steps ?? []) {
192
+ if (
193
+ typeof s.uses === "string" &&
194
+ s.uses.startsWith("oven-sh/setup-bun") &&
195
+ s.with?.["bun-version"] !== undefined
196
+ ) {
197
+ f(
198
+ "workflows/bun-from-package-manager",
199
+ where,
200
+ `job \`${job}\` sets \`bun-version\`; setup-bun reads \`packageManager\``,
201
+ );
202
+ }
203
+ }
204
+ }
205
+ for (const { job, line } of runLines(wf)) {
206
+ for (const cmd of parseScript(line)) {
207
+ const [bin, sub] = cmd.argv;
208
+ if (bin === "bunx" || (bin === "bun" && sub === "x")) {
209
+ f("workflows/scripts-only", where, `job \`${job}\`: \`${cmd.raw}\`; call a script`);
210
+ } else if (bin === "bun" && sub === "install" && !cmd.argv.includes("--frozen-lockfile")) {
211
+ f(
212
+ "workflows/scripts-only",
213
+ where,
214
+ `job \`${job}\`: \`${cmd.raw}\` without \`--frozen-lockfile\``,
215
+ );
216
+ } else if (bin === "bun" && sub !== "install" && !asBunRun(cmd)) {
217
+ f(
218
+ "workflows/scripts-only",
219
+ where,
220
+ `job \`${job}\`: \`${cmd.raw}\` is inline; make it a script`,
221
+ );
222
+ }
223
+ if (
224
+ bin === "bun" &&
225
+ (sub === "install" || sub === "i") &&
226
+ cmd.argv.includes("--ignore-scripts")
227
+ ) {
228
+ f(
229
+ "workflows/scripts-only",
230
+ where,
231
+ `job \`${job}\`: \`--ignore-scripts\` skips the Effect patch`,
232
+ );
233
+ }
234
+ }
235
+ }
236
+
237
+ if (name === "ci.yml") {
238
+ const got = stripRef(normalizeCi(wf, repo));
239
+ const want = stripRef(structuredClone(ref));
240
+ const gotCode = new Set(takeCode(got));
241
+ const wantCode = takeCode(want);
242
+ for (const p of wantCode.filter((x) => !gotCode.has(x))) {
243
+ f(
244
+ "workflows/ci-reference",
245
+ where,
246
+ `the \`code\` filter lacks "${p}"; declare it in \`ci.ignoreRemove\` if intended`,
247
+ );
248
+ }
249
+ for (const p of [...gotCode].filter((x) => !wantCode.includes(x))) {
250
+ f(
251
+ "workflows/ci-reference",
252
+ where,
253
+ `the \`code\` filter has "${p}"; declare it in \`ci.ignoreAdd\` if intended`,
254
+ );
255
+ }
256
+ for (const d of diffPaths(want, got)) {
257
+ f("workflows/ci-reference", where, d);
258
+ }
259
+ }
260
+
261
+ const tags = wf.on?.push?.tags;
262
+ if (tags !== undefined) {
263
+ out.push(...releaseRules(repo, where, wf));
264
+ }
265
+ }
266
+ return out;
267
+ };
268
+
269
+ const releaseRules = (repo: Repo, where: string, wf: any): Finding[] => {
270
+ const out: Finding[] = [];
271
+ const lines = runLines(wf);
272
+ const runs = lines.flatMap(({ job, line }) =>
273
+ parseScript(line).map((cmd) => ({ job, cmd, run: asBunRun(cmd) })),
274
+ );
275
+ if (!runs.some((r) => r.run?.script === "check")) {
276
+ out.push({
277
+ rule: "workflows/release-check",
278
+ where,
279
+ message: "no job runs `bun run check` before releasing",
280
+ });
281
+ }
282
+ if (!lines.some(({ line }) => line.includes("GITHUB_REF_NAME#v"))) {
283
+ out.push({
284
+ rule: "workflows/release-version",
285
+ where,
286
+ message: "no step checks the tag against the package version",
287
+ });
288
+ }
289
+ const builds = runs.filter((r) => r.run?.script.startsWith("build:"));
290
+ if (builds.length === 0) {
291
+ out.push({
292
+ rule: "workflows/release-build",
293
+ where,
294
+ message: "no step calls a `build:<target>` script",
295
+ });
296
+ }
297
+ for (const b of builds) {
298
+ const pkg = repo.pkgAt(b.run!.cwd ?? ".");
299
+ const job = wf.jobs[b.job];
300
+ const targets: string[] = (job?.strategy?.matrix?.include ?? [])
301
+ .map((m: any) => m.target)
302
+ .filter(Boolean);
303
+ const names = b.run!.script.includes("${{ matrix.target }}")
304
+ ? targets.map((t) => b.run!.script.replace("${{ matrix.target }}", t))
305
+ : [b.run!.script];
306
+ for (const n of names) {
307
+ if (pkg?.scripts[n] === undefined) {
308
+ out.push({
309
+ rule: "workflows/release-build",
310
+ where,
311
+ message: `calls \`${n}\`, which ${pkg?.dir ?? b.run!.cwd} does not define`,
312
+ });
313
+ }
314
+ }
315
+ }
316
+ return out;
317
+ };
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.