@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.
package/src/pins.ts ADDED
@@ -0,0 +1,233 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import { join, relative } from "node:path";
3
+
4
+ import type { Finding } from "./finding.ts";
5
+ import { catalogs, type Pkg, readJsonc, type Repo } from "./repo.ts";
6
+
7
+ const EXACT = /^(npm:(@[\w.-]+\/)?[\w.-]+@)?\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/;
8
+ const PINNED_GIT = /^(github:|git\+[a-z]+:\/\/|https:\/\/github\.com\/)[^#]+#[0-9a-f]{40}$/;
9
+ const PREPARE = "effect-tsgo patch --no-typescript --tsrs --oxlint";
10
+ const ROOT_TOOLS = ["@effect/tsgo", "@oxlint/plugins", "oxfmt", "oxlint", "tsrs"];
11
+ const TSGO_PLATFORMS = [
12
+ "darwin-arm64",
13
+ "darwin-x64",
14
+ "linux-arm",
15
+ "linux-arm64",
16
+ "linux-x64",
17
+ "win32-arm64",
18
+ "win32-x64",
19
+ ].map((p) => `@effect/tsgo-${p}`);
20
+ const STRICT_FLAGS = [
21
+ "strict",
22
+ "noUncheckedIndexedAccess",
23
+ "noImplicitOverride",
24
+ "noFallthroughCasesInSwitch",
25
+ "exactOptionalPropertyTypes",
26
+ ];
27
+ const DEP_FIELDS = ["dependencies", "devDependencies", "optionalDependencies"] as const;
28
+
29
+ const depsOf = (pkg: Pkg): [string, string][] =>
30
+ DEP_FIELDS.flatMap((field) => Object.entries<string>(pkg.json[field] ?? {}));
31
+
32
+ export const pinRules = (repo: Repo): Finding[] => {
33
+ const out: Finding[] = [];
34
+ const root = repo.rootPkg;
35
+ const cats = catalogs(repo);
36
+ const f = (rule: string, where: string, message: string, script?: string) =>
37
+ out.push({ rule, where, script, message });
38
+
39
+ const pm = root.json.packageManager;
40
+ if (typeof pm !== "string" || !/^bun@\d+\.\d+\.\d+$/.test(pm))
41
+ f(
42
+ "pins/package-manager",
43
+ ".",
44
+ `\`packageManager\` must be \`bun@<exact>\`; got ${JSON.stringify(pm)}`,
45
+ );
46
+ const bunVersion = typeof pm === "string" ? pm.slice(4) : undefined;
47
+
48
+ for (const [name, entries] of cats) {
49
+ for (const [dep, spec] of Object.entries(entries)) {
50
+ if (!EXACT.test(spec) && !PINNED_GIT.test(spec))
51
+ f(
52
+ "pins/exact",
53
+ ".",
54
+ `catalog \`${name || "default"}\`: \`${dep}\` is \`${spec}\`, not an exact version`,
55
+ );
56
+ }
57
+ }
58
+ const resolve = (dep: string, spec: string): string | undefined => {
59
+ if (!spec.startsWith("catalog:")) return spec;
60
+ return cats.get(spec.slice(8))?.[dep];
61
+ };
62
+ const catalogued = new Set([...cats.values()].flatMap((e) => Object.keys(e)));
63
+
64
+ for (const pkg of [root, ...repo.workspaces]) {
65
+ for (const [dep, spec] of depsOf(pkg)) {
66
+ if (spec.startsWith("catalog:")) {
67
+ if (resolve(dep, spec) === undefined)
68
+ f("pins/exact", pkg.dir, `\`${dep}\`: \`${spec}\` has no entry for it`);
69
+ } else if (spec.startsWith("workspace:")) {
70
+ continue;
71
+ } else if (!EXACT.test(spec) && !PINNED_GIT.test(spec)) {
72
+ f("pins/exact", pkg.dir, `\`${dep}\` is \`${spec}\`, not an exact version`);
73
+ } else if (repo.isWorkspace && catalogued.has(dep)) {
74
+ f(
75
+ "pins/use-catalog",
76
+ pkg.dir,
77
+ `\`${dep}\` is in a root catalog; use \`catalog:\` instead of \`${spec}\``,
78
+ );
79
+ }
80
+ if (dep === "oxlint-tsgolint")
81
+ f(
82
+ "pins/toolchain-deps",
83
+ pkg.dir,
84
+ "`oxlint-tsgolint` is not used: tsrs serves type-aware lint",
85
+ );
86
+ if (dep === "typescript" && pkg.toolchain !== "astro" && pkg.toolchain !== "pulumi") {
87
+ f(
88
+ "pins/toolchain-deps",
89
+ pkg.dir,
90
+ "`typescript` is only for Astro docs and Pulumi packages; tsrs is the compiler",
91
+ );
92
+ }
93
+ if ((dep === "bun-types" || dep === "@types/bun") && bunVersion !== undefined) {
94
+ const v = resolve(dep, spec);
95
+ if (v !== bunVersion)
96
+ f(
97
+ "pins/bun-types",
98
+ pkg.dir,
99
+ `\`${dep}\` is ${v}, \`packageManager\` is bun@${bunVersion}`,
100
+ );
101
+ }
102
+ }
103
+ }
104
+ const rootDev = root.json.devDependencies ?? {};
105
+ for (const tool of ROOT_TOOLS) {
106
+ if (rootDev[tool] === undefined)
107
+ f("pins/toolchain-deps", ".", `root \`devDependencies\` lacks \`${tool}\``);
108
+ }
109
+ if (root.scripts.prepare !== PREPARE)
110
+ f("pins/prepare", ".", `expected \`${PREPARE}\`; got \`${root.scripts.prepare}\``, "prepare");
111
+
112
+ // bunfig.toml
113
+ const bunfigPath = join(repo.root, "bunfig.toml");
114
+ if (!existsSync(bunfigPath)) {
115
+ f("pins/bunfig", ".", "no `bunfig.toml`");
116
+ } else {
117
+ const install: any = (Bun.TOML.parse(readFileSync(bunfigPath, "utf8")) as any).install ?? {};
118
+ if (typeof install.minimumReleaseAge !== "number" || install.minimumReleaseAge < 86400) {
119
+ f(
120
+ "pins/bunfig",
121
+ "bunfig.toml",
122
+ `\`[install] minimumReleaseAge\` must be at least 86400; got ${JSON.stringify(install.minimumReleaseAge)}`,
123
+ );
124
+ }
125
+ const excludes: string[] = install.minimumReleaseAgeExcludes ?? [];
126
+ const missing = ["@effect/tsgo", ...TSGO_PLATFORMS].filter((p) => !excludes.includes(p));
127
+ // This package ships from the same scope; without it a new release waits a day to install.
128
+ if (!excludes.includes("@jfalava/*") && !excludes.includes("@jfalava/ts-standard"))
129
+ missing.push("@jfalava/*");
130
+ if (missing.length > 0)
131
+ f("pins/bunfig", "bunfig.toml", `\`minimumReleaseAgeExcludes\` lacks ${missing.join(", ")}`);
132
+ }
133
+
134
+ out.push(...tsconfigRules(repo));
135
+ return out;
136
+ };
137
+
138
+ const pluginEntry = (tsconfig: any) =>
139
+ (tsconfig?.compilerOptions?.plugins ?? []).find(
140
+ (p: { name?: string }) => p.name === "@effect/language-service",
141
+ );
142
+
143
+ /** The tsconfig files of the root and of each workspace package. */
144
+ const tsconfigsOf = (repo: Repo): string[] =>
145
+ [repo.rootPkg, ...repo.workspaces].flatMap((pkg) =>
146
+ readdirSync(pkg.abs)
147
+ .filter((n) => /^tsconfig(\..+)?\.json$/.test(n))
148
+ .map((n) => join(pkg.abs, n)),
149
+ );
150
+
151
+ const tsconfigRules = (repo: Repo): Finding[] => {
152
+ const out: Finding[] = [];
153
+ const baseName = repo.isWorkspace ? "tsconfig.base.json" : "tsconfig.json";
154
+ const basePath = join(repo.root, baseName);
155
+ if (!existsSync(basePath)) {
156
+ out.push({ rule: "tsconfig/base", where: baseName, message: "missing" });
157
+ return out;
158
+ }
159
+ const base: any = readJsonc(basePath);
160
+ const co = base.compilerOptions ?? {};
161
+ if (base.$schema !== "./node_modules/@effect/tsgo/schema.json")
162
+ out.push({
163
+ rule: "tsconfig/base",
164
+ where: baseName,
165
+ message: "`$schema` must be `./node_modules/@effect/tsgo/schema.json`",
166
+ });
167
+ if (!pluginEntry(base))
168
+ out.push({
169
+ rule: "tsconfig/effect-plugin",
170
+ where: baseName,
171
+ message: "no `@effect/language-service` plugin entry; Effect diagnostics are off",
172
+ });
173
+ if (co.noEmit !== true)
174
+ out.push({ rule: "tsconfig/no-emit", where: baseName, message: "`noEmit` must be true" });
175
+ for (const flag of ["strict", "noUncheckedIndexedAccess"]) {
176
+ if (co[flag] !== true)
177
+ out.push({
178
+ rule: "tsconfig/strict-in-base",
179
+ where: baseName,
180
+ message: `\`${flag}\` must be true in the base`,
181
+ });
182
+ }
183
+ for (const path of tsconfigsOf(repo)) {
184
+ const rel = relative(repo.root, path);
185
+ const ts: any = readJsonc(path);
186
+ if (pluginEntry(ts)?.ignoreEffectWarningsInTscExitCode === true) {
187
+ out.push({
188
+ rule: "tsconfig/no-ignore-effect-warnings",
189
+ where: rel,
190
+ message: "`ignoreEffectWarningsInTscExitCode: true` lets Effect warnings pass the gate",
191
+ });
192
+ }
193
+ }
194
+ if (!repo.isWorkspace) return out;
195
+ for (const pkg of repo.workspaces) {
196
+ if (pkg.toolchain === "astro" || pkg.toolchain === "pulumi") continue;
197
+ const p = join(pkg.abs, "tsconfig.json");
198
+ if (!existsSync(p)) {
199
+ out.push({ rule: "tsconfig/extends-base", where: pkg.dir, message: "no `tsconfig.json`" });
200
+ continue;
201
+ }
202
+ const ts: any = readJsonc(p);
203
+ const ext = [ts.extends ?? []].flat();
204
+ const want = relative(pkg.abs, basePath);
205
+ if (!ext.includes(want) && !ext.includes(`./${want}`))
206
+ out.push({
207
+ rule: "tsconfig/extends-base",
208
+ where: `${pkg.dir}/tsconfig.json`,
209
+ message: `must extend \`${want}\``,
210
+ });
211
+ const set = STRICT_FLAGS.filter((k) => ts.compilerOptions?.[k] !== undefined);
212
+ if (set.length > 0)
213
+ out.push({
214
+ rule: "tsconfig/strict-in-base",
215
+ where: `${pkg.dir}/tsconfig.json`,
216
+ message: `sets ${set.join(", ")}; strict flags belong in the base`,
217
+ });
218
+ if (ts.compilerOptions?.plugins !== undefined)
219
+ out.push({
220
+ rule: "tsconfig/effect-plugin",
221
+ where: `${pkg.dir}/tsconfig.json`,
222
+ message: "overrides `plugins`; the Effect policy lives in the base",
223
+ });
224
+ const extra = readdirSync(pkg.abs).filter((n) => /^tsconfig\..+\.json$/.test(n));
225
+ if (extra.length > 0)
226
+ out.push({
227
+ rule: "tsconfig/one-per-package",
228
+ where: pkg.dir,
229
+ message: `${extra.join(", ")}: list tests in \`tsconfig.json\`'s \`include\` instead`,
230
+ });
231
+ }
232
+ return out;
233
+ };
package/src/repo.ts ADDED
@@ -0,0 +1,84 @@
1
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
2
+ import { basename, join } from "node:path";
3
+
4
+ import type { StandardConfig, Toolchain } from "./config.ts";
5
+
6
+ export interface Pkg {
7
+ /** Repo-relative directory, "." for the root. */
8
+ readonly dir: string;
9
+ readonly abs: string;
10
+ readonly json: any;
11
+ readonly scripts: Readonly<Record<string, string>>;
12
+ readonly toolchain: Toolchain;
13
+ }
14
+
15
+ export interface Repo {
16
+ readonly name: string;
17
+ readonly root: string;
18
+ readonly config: StandardConfig;
19
+ readonly rootPkg: Pkg;
20
+ /** Workspace packages, excluding the root. Empty for single-package repos. */
21
+ readonly workspaces: readonly Pkg[];
22
+ readonly isWorkspace: boolean;
23
+ pkgAt(dir: string): Pkg | undefined;
24
+ }
25
+
26
+ export const readJsonc = (path: string): unknown => Bun.JSONC.parse(readFileSync(path, "utf8"));
27
+
28
+ const loadPkg = (root: string, dir: string, config: StandardConfig): Pkg => {
29
+ const abs = join(root, dir);
30
+ const json = JSON.parse(readFileSync(join(abs, "package.json"), "utf8"));
31
+ return {
32
+ dir,
33
+ abs,
34
+ json,
35
+ scripts: json.scripts ?? {},
36
+ toolchain: config.toolchains?.[dir] ?? "oxc",
37
+ };
38
+ };
39
+
40
+ const expandWorkspaceGlobs = (root: string, patterns: readonly string[]): string[] => {
41
+ const dirs: string[] = [];
42
+ for (const pattern of patterns) {
43
+ if (pattern.endsWith("/*")) {
44
+ const parent = pattern.slice(0, -2);
45
+ for (const entry of readdirSync(join(root, parent), { withFileTypes: true })) {
46
+ if (entry.isDirectory() && existsSync(join(root, parent, entry.name, "package.json"))) {
47
+ dirs.push(`${parent}/${entry.name}`);
48
+ }
49
+ }
50
+ } else if (existsSync(join(root, pattern, "package.json"))) {
51
+ dirs.push(pattern);
52
+ }
53
+ }
54
+ return dirs;
55
+ };
56
+
57
+ export const loadRepo = (root: string, config: StandardConfig): Repo => {
58
+ const rootPkg = loadPkg(root, ".", config);
59
+ const ws = rootPkg.json.workspaces;
60
+ const patterns: string[] = Array.isArray(ws) ? ws : (ws?.packages ?? []);
61
+ const workspaces = expandWorkspaceGlobs(root, patterns).map((dir) => loadPkg(root, dir, config));
62
+ const all = [rootPkg, ...workspaces];
63
+ return {
64
+ name: basename(root),
65
+ root,
66
+ config,
67
+ rootPkg,
68
+ workspaces,
69
+ isWorkspace: patterns.length > 0,
70
+ pkgAt: (dir) => {
71
+ const d = dir.replace(/^\.\//, "").replace(/\/$/, "") || ".";
72
+ return all.find((p) => p.dir === d);
73
+ },
74
+ };
75
+ };
76
+
77
+ export const catalogs = (repo: Repo): Map<string, Record<string, string>> => {
78
+ const ws = repo.rootPkg.json.workspaces ?? {};
79
+ const out = new Map<string, Record<string, string>>();
80
+ if (ws.catalog) out.set("", ws.catalog);
81
+ for (const [name, entries] of Object.entries(ws.catalogs ?? {}))
82
+ out.set(name, entries as Record<string, string>);
83
+ return out;
84
+ };