@avi2dg/checks 0.6.0 → 0.8.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.
@@ -1,8 +1,9 @@
1
1
  #!/usr/bin/env bun
2
- import { parseSync } from "@swc/core";
3
- import { readFile } from "node:fs/promises";
4
- import { join } from "node:path";
5
- import { fileURLToPath } from "node:url";
2
+ import { parse } from "@swc/core";
3
+ import { Console, Effect, FileSystem, Path, Schema } from "effect";
4
+ import { git } from "./git.ts";
5
+ import { runMain } from "./main.ts";
6
+ import { ENTRY_POINT } from "./gates.ts";
6
7
 
7
8
  export type Violation = {
8
9
  readonly file: string;
@@ -44,11 +45,21 @@ const REQUIRED_TEST_TABLE: Record<string, unknown> = {
44
45
  };
45
46
  export const LAYOUT_CHECK_MARK = "scripts/test-layout.ts";
46
47
  export const LAYOUT_CHECK_BIN = "checks-test-layout";
48
+ const OWN_ENTRY_POINT = `scripts/${ENTRY_POINT.script}`;
49
+
50
+ export class LayoutError extends Schema.TaggedError<LayoutError>()("LayoutError", {
51
+ message: Schema.String,
52
+ }) {}
47
53
 
48
54
  function isRecord(value: unknown): value is Record<string, unknown> {
49
55
  return typeof value === "object" && value !== null;
50
56
  }
51
57
 
58
+ function runsLayoutCheck(lint: string): boolean {
59
+ if (lint.includes(LAYOUT_CHECK_MARK) || lint.includes(LAYOUT_CHECK_BIN)) return true;
60
+ return lint.split(/[\s|&;()]+/).some((word) => word === ENTRY_POINT.bin || word === OWN_ENTRY_POINT);
61
+ }
62
+
52
63
  function startsWithAny(file: string, prefixes: readonly string[]): boolean {
53
64
  return prefixes.some((prefix) => file.startsWith(prefix));
54
65
  }
@@ -177,8 +188,11 @@ function outOfProcessUse(node: Record<string, unknown>): string | undefined {
177
188
  return undefined;
178
189
  }
179
190
 
180
- export function isolationViolations(file: string, source: string): readonly Violation[] {
181
- const module = parseSync(source, { syntax: "typescript", tsx: file.endsWith(".tsx"), target: "esnext" });
191
+ export const isolationViolations = Effect.fn("isolationViolations")(function* (file: string, source: string) {
192
+ const module = yield* Effect.tryPromise({
193
+ try: () => parse(source, { syntax: "typescript", tsx: file.endsWith(".tsx"), target: "esnext" }),
194
+ catch: (error) => new LayoutError({ message: `cannot parse ${file}: ${String(error)}` }),
195
+ });
182
196
  const violations: Violation[] = [];
183
197
  const seen = new Set<unknown>();
184
198
 
@@ -204,7 +218,7 @@ export function isolationViolations(file: string, source: string): readonly Viol
204
218
 
205
219
  visit(module);
206
220
  return violations;
207
- }
221
+ });
208
222
 
209
223
  export function scriptViolations(manifest: unknown): readonly Violation[] {
210
224
  const file = "package.json";
@@ -219,11 +233,11 @@ export function scriptViolations(manifest: unknown): readonly Violation[] {
219
233
  message: `scripts.test must be exactly "${REQUIRED_TEST_SCRIPT}", found ${JSON.stringify(test ?? null)}`,
220
234
  });
221
235
  }
222
- if (typeof lint !== "string" || (!lint.includes(LAYOUT_CHECK_MARK) && !lint.includes(LAYOUT_CHECK_BIN))) {
236
+ if (typeof lint !== "string" || !runsLayoutCheck(lint)) {
223
237
  violations.push({
224
238
  file,
225
239
  line: undefined,
226
- message: `scripts.lint must run the layout check: add "${LAYOUT_CHECK_BIN}"`,
240
+ message: `scripts.lint must run the layout check: add "${ENTRY_POINT.bin}"`,
227
241
  });
228
242
  }
229
243
  return violations;
@@ -255,30 +269,38 @@ export function bunfigViolations(consumer: unknown, preset: unknown): readonly V
255
269
  return violations;
256
270
  }
257
271
 
258
- async function workingTreeFiles(root: string): Promise<readonly string[]> {
259
- const listed = Bun.spawnSync(["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard"], { cwd: root });
260
- if (listed.exitCode !== 0) {
261
- throw new Error(`test-layout: git ls-files failed in ${root}: ${listed.stderr.toString()}`);
262
- }
263
- const listedFiles = listed.stdout.toString().split("\0").filter(Boolean);
264
- const present = await Promise.all(listedFiles.map((file) => Bun.file(join(root, file)).exists()));
265
- return listedFiles.filter((_, index) => present[index]);
266
- }
267
-
268
- async function parsedToml(path: string): Promise<unknown> {
269
- const imported: unknown = await import(path);
270
- return isRecord(imported) ? (imported["default"] ?? imported) : imported;
271
- }
272
-
273
- async function readManifest(root: string): Promise<unknown> {
274
- const text = await readFile(join(root, "package.json"), "utf8");
275
- return JSON.parse(text) as unknown;
276
- }
272
+ const workingTreeFiles = Effect.fn("workingTreeFiles")(function* (root: string) {
273
+ const fs = yield* FileSystem.FileSystem;
274
+ const path = yield* Path.Path;
275
+ const listed = yield* git(["ls-files", "-z", "--cached", "--others", "--exclude-standard"], root);
276
+ return yield* Effect.filter(listed.split("\0").filter(Boolean), (file) => fs.exists(path.join(root, file)), {
277
+ concurrency: "unbounded",
278
+ });
279
+ });
280
+
281
+ const parsedToml = Effect.fn("parsedToml")(function* (file: string) {
282
+ const text = yield* (yield* FileSystem.FileSystem).readFileString(file);
283
+ return yield* Effect.try({
284
+ try: (): unknown => Bun.TOML.parse(text),
285
+ catch: (error) => new LayoutError({ message: `cannot parse ${file}: ${String(error)}` }),
286
+ });
287
+ });
288
+
289
+ const parseJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
290
+
291
+ const readManifest = Effect.fn("readManifest")(function* (file: string) {
292
+ const text = yield* (yield* FileSystem.FileSystem).readFileString(file);
293
+ return yield* parseJson(text).pipe(
294
+ Effect.mapError((cause) => new LayoutError({ message: `cannot read ${file} as JSON: ${cause.message}` })),
295
+ );
296
+ });
277
297
 
278
298
  export type Result = { readonly files: number; readonly violations: readonly Violation[] };
279
299
 
280
- export async function run(root: string, presetPath: string): Promise<Result> {
281
- const files = await workingTreeFiles(root);
300
+ export const run = Effect.fn("run")(function* (root: string, presetPath: string) {
301
+ const fs = yield* FileSystem.FileSystem;
302
+ const path = yield* Path.Path;
303
+ const files = yield* workingTreeFiles(root);
282
304
  const violations: Violation[] = [...placementViolations(files)];
283
305
 
284
306
  const inProcess = files.filter(
@@ -289,19 +311,18 @@ export async function run(root: string, presetPath: string): Promise<Result> {
289
311
  !file.startsWith(DATA_DIR),
290
312
  );
291
313
  for (const file of inProcess) {
292
- const source = await readFile(join(root, file), "utf8");
293
- violations.push(...isolationViolations(file, source));
314
+ const source = yield* fs.readFileString(path.join(root, file));
315
+ violations.push(...(yield* isolationViolations(file, source)));
294
316
  }
295
317
 
296
- violations.push(...scriptViolations(await readManifest(root)));
318
+ violations.push(...scriptViolations(yield* readManifest(path.join(root, "package.json"))));
297
319
 
298
- const consumerBunfig = (await Bun.file(join(root, "bunfig.toml")).exists())
299
- ? await parsedToml(join(root, "bunfig.toml"))
300
- : undefined;
301
- violations.push(...bunfigViolations(consumerBunfig, await parsedToml(presetPath)));
320
+ const bunfig = path.join(root, "bunfig.toml");
321
+ const consumerBunfig = (yield* fs.exists(bunfig)) ? yield* parsedToml(bunfig) : undefined;
322
+ violations.push(...bunfigViolations(consumerBunfig, yield* parsedToml(presetPath)));
302
323
 
303
324
  return { files: files.length, violations };
304
- }
325
+ });
305
326
 
306
327
  export function report({ files, violations }: Result): string {
307
328
  if (violations.length === 0) return `test-layout: ${files} files satisfy the layout`;
@@ -312,10 +333,12 @@ export function report({ files, violations }: Result): string {
312
333
  return [`test-layout: ${violations.length} violation(s)`, ...lines].join("\n");
313
334
  }
314
335
 
315
- if (import.meta.main) {
336
+ const layout = Effect.gen(function* () {
337
+ const path = yield* Path.Path;
316
338
  const root = process.argv[2] ?? process.cwd();
317
- const preset = fileURLToPath(new URL("../bunfig.toml", import.meta.url));
318
- const result = await run(root, preset);
319
- console.log(report(result));
320
- process.exit(result.violations.length === 0 ? 0 : 1);
321
- }
339
+ const result = yield* run(root, path.join(import.meta.dir, "..", "bunfig.toml"));
340
+ yield* Console.log(report(result));
341
+ return result.violations.length === 0;
342
+ });
343
+
344
+ if (import.meta.main) runMain("test-layout", layout);