@aklinker1/check 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Aaron Klinker
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,46 @@
1
+ # Check
2
+
3
+ An opinionated CLI tool to run all your checks all at once. The command will only exit with code 0 when no warnings exist.
4
+
5
+ https://github.com/aklinker1/check/assets/10101283/c8089e5c-e25f-4f59-8897-d2a6f97a3139
6
+
7
+ > [!WARNING]
8
+ > I have not actually published this to NPM yet.
9
+
10
+ ```sh
11
+ pnpm i @aklinker1/check
12
+ pnpm check
13
+ pnpm check --fix
14
+ ```
15
+
16
+ To enable checks for any of the following modules, just install them:
17
+
18
+ ```sh
19
+ pnpm i -D typescript eslint prettier publint
20
+ ```
21
+
22
+ ## Contributing
23
+
24
+ This project is built using [`bun`](https://bun.sh). Demo project uses PNPM.
25
+
26
+ ```sh
27
+ # Setup
28
+ bun i
29
+ pushd demo
30
+ pnpm i
31
+ popd
32
+
33
+ # Build NPM package
34
+ bun run build
35
+
36
+ # Run checks
37
+ bun check --help
38
+ bun check
39
+ bun check demo
40
+ ```
41
+
42
+ ### Adding Tools
43
+
44
+ I've added everything I use, so if you want to add support for another tool, feel free.
45
+
46
+ Just copy `src/tools/prettier.ts` and `src/tools/prettier.test.ts`, update the implementations (yes, tests are required), and add your new tool to `src/tools/index.ts`'s `ALL_TOOLS` export.
package/bin/check.mjs ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import "../dist/cli.mjs";
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/cli.mjs ADDED
@@ -0,0 +1,29 @@
1
+ import { defineCommand, runMain } from "citty";
2
+ import { check } from "./index.mjs";
3
+ const main = defineCommand({
4
+ meta: {
5
+ name: "check",
6
+ description: "@aklinker1/check"
7
+ },
8
+ args: {
9
+ root: {
10
+ type: "positional",
11
+ description: "Root directory to run commands from",
12
+ required: false
13
+ },
14
+ fix: {
15
+ type: "boolean",
16
+ alias: "f",
17
+ description: "Fix problems if possible instead of just reporting them"
18
+ },
19
+ debug: {
20
+ type: "boolean",
21
+ alias: "d",
22
+ description: "Enable debug logs"
23
+ }
24
+ },
25
+ async run(ctx) {
26
+ await check(ctx.args);
27
+ }
28
+ });
29
+ runMain(main);
@@ -0,0 +1,4 @@
1
+ import type { CheckOptions, Problem } from "./types";
2
+ export type * from "./types";
3
+ export declare function check(options?: CheckOptions): Promise<void>;
4
+ export declare function renderProblem(problem: Problem): string;
package/dist/index.mjs ADDED
@@ -0,0 +1,103 @@
1
+ import { ALL_TOOLS } from "./tools/index.mjs";
2
+ import { p } from "@antfu/utils";
3
+ import { bold, cyan, debug, dim, humanMs, isDebug, red, yellow } from "./utils.mjs";
4
+ import { createTaskList } from "./tasklist/index.mjs";
5
+ import { relative, resolve, sep } from "node:path";
6
+ export async function check(options = {}) {
7
+ const { debug: debug2, fix, root } = options;
8
+ if (debug2) {
9
+ process.env.DEBUG = "true";
10
+ }
11
+ console.log();
12
+ const tools = await findInstalledTools(root);
13
+ if (tools.length === 0) {
14
+ console.log("No tools detected! Run with --debug for more info");
15
+ console.log();
16
+ process.exit(1);
17
+ }
18
+ const results = await createTaskList(
19
+ tools,
20
+ async ({ input: tool, fail, succeed, warn }) => {
21
+ const startTime = performance.now();
22
+ const fn = fix ? tool.fix ?? tool.check : tool.check;
23
+ const output = await fn(root);
24
+ if ("problems" in output) {
25
+ output.problems.forEach((problem) => {
26
+ problem.file = resolve(root ?? process.cwd(), problem.file);
27
+ });
28
+ }
29
+ const duration = humanMs(performance.now() - startTime);
30
+ const title = `${tool.name} ${dim(`(${duration})`)}`;
31
+ if (output.type === "error")
32
+ fail(title);
33
+ else if (output.type === "warning")
34
+ warn(title);
35
+ else
36
+ succeed(title);
37
+ return output;
38
+ }
39
+ );
40
+ const problems = results.flatMap((result) => result.type === "success" ? [] : result.problems).sort((l, r) => {
41
+ const nameCompare = l.file.localeCompare(r.file);
42
+ if (nameCompare !== 0)
43
+ return nameCompare;
44
+ const lineCompare = (l.location?.line ?? 0) - (r.location?.line ?? 0);
45
+ if (lineCompare !== 0)
46
+ return lineCompare;
47
+ return (l.location?.column ?? 0) - (r.location?.column ?? 0);
48
+ });
49
+ console.log();
50
+ if (problems.length === 0) {
51
+ process.exit(0);
52
+ }
53
+ console.log(plural(problems.length, "Problem:", "Problems:"));
54
+ problems.forEach((problem) => {
55
+ console.log(renderProblem(problem));
56
+ });
57
+ const files = Object.entries(
58
+ problems.reduce((acc, problem) => {
59
+ const file = "." + sep + relative(process.cwd(), problem.file);
60
+ acc[file] ??= 0;
61
+ acc[file]++;
62
+ return acc;
63
+ }, {})
64
+ );
65
+ const maxLength = files.reduce(
66
+ (prev, [file]) => Math.max(prev, file.length),
67
+ 0
68
+ );
69
+ console.log();
70
+ console.log("Across " + plural(files.length, "File:", "Files:"));
71
+ files.forEach(([file, count]) => {
72
+ console.log(`${cyan(file.padEnd(maxLength, " "))} ${count}`);
73
+ });
74
+ console.log();
75
+ const failedChecks = results.filter((res) => res.type === "error").length;
76
+ process.exit(failedChecks);
77
+ }
78
+ async function findInstalledTools(root) {
79
+ const status = await p(ALL_TOOLS).map(async (tool) => ({
80
+ tool,
81
+ isInstalled: await tool.isInstalled(root)
82
+ })).promise;
83
+ if (isDebug()) {
84
+ const getTools = (isInstalled) => status.filter((item) => item.isInstalled === isInstalled).map((item) => item.tool.name).join(", ");
85
+ const installed = getTools(true);
86
+ debug(`Installed: ${installed || "(none)"}`);
87
+ const skipped = getTools(false);
88
+ debug(`Skipping: ${skipped || "(none)"} `);
89
+ }
90
+ return status.filter(({ isInstalled }) => isInstalled).map((item) => item.tool);
91
+ }
92
+ function plural(count, singular, plural2) {
93
+ return `${count} ${count === 1 ? singular : plural2} `;
94
+ }
95
+ export function renderProblem(problem) {
96
+ const icon = problem.kind === "warning" ? bold(yellow("\u26A0")) : bold(red("\u2717"));
97
+ const path = relative(process.cwd(), problem.file);
98
+ const location = problem.location ? `${path}:${problem.location.line}:${problem.location.column}` : path;
99
+ const source = problem.rule ? dim(` (${problem.rule})`) : "";
100
+ const link = dim(`\u2192 .${sep}${location}`);
101
+ return `${icon} ${problem.message}${source}
102
+ ${link}`;
103
+ }
@@ -0,0 +1,8 @@
1
+ export declare function createTaskList<TInput extends {
2
+ name: string;
3
+ }, TResult = void>(inputs: TInput[], run: (ctx: {
4
+ input: TInput;
5
+ succeed: (title?: string) => void;
6
+ warn: (title?: string) => void;
7
+ fail: (title?: string) => void;
8
+ }) => Promise<TResult>): Promise<TResult[]>;
@@ -0,0 +1,76 @@
1
+ import { cyan, dim, green, red, yellow } from "../utils.mjs";
2
+ import readline from "node:readline";
3
+ export async function createTaskList(inputs, run) {
4
+ const states = inputs.map((item) => ({
5
+ title: item.name,
6
+ state: "pending"
7
+ }));
8
+ const isTty = process.stderr.isTTY;
9
+ let tick = 0;
10
+ const render = (opts) => {
11
+ if (!opts?.firstRender) {
12
+ readline.moveCursor(process.stderr, 0, -1 * states.length);
13
+ }
14
+ states.forEach(({ state, title }) => {
15
+ readline.clearLine(process.stderr, 0);
16
+ const frames = SPINNER_FRAMES[state];
17
+ process.stderr.write(`${frames[tick % frames.length]} ${title}
18
+ `);
19
+ });
20
+ tick++;
21
+ };
22
+ render({ firstRender: true });
23
+ const renderInterval = setInterval(render, SPINNER_INTERVAL_MS);
24
+ try {
25
+ const result = Promise.all(
26
+ inputs.map(async (input, i) => {
27
+ const succeed = (title) => {
28
+ if (title != null)
29
+ states[i].title = title;
30
+ states[i].state = "success";
31
+ render();
32
+ };
33
+ const warn = (title) => {
34
+ if (title != null)
35
+ states[i].title = title;
36
+ states[i].state = "warning";
37
+ render();
38
+ };
39
+ const fail = (title) => {
40
+ if (title != null)
41
+ states[i].title = title;
42
+ states[i].state = "error";
43
+ render();
44
+ };
45
+ try {
46
+ states[i].state = "in-progress";
47
+ render();
48
+ const res = await run({ input, succeed, warn, fail });
49
+ if (states[i].state === "in-progress") {
50
+ states[i].state = "success";
51
+ render();
52
+ }
53
+ return res;
54
+ } catch (err) {
55
+ if (err instanceof Error)
56
+ fail(err.message);
57
+ else
58
+ fail(String(err));
59
+ throw err;
60
+ }
61
+ })
62
+ );
63
+ render({ lastRender: true });
64
+ return await result;
65
+ } finally {
66
+ clearInterval(renderInterval);
67
+ }
68
+ }
69
+ const SPINNER_INTERVAL_MS = 80;
70
+ const SPINNER_FRAMES = {
71
+ pending: [dim("\u25A1")],
72
+ "in-progress": ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"].map(cyan),
73
+ success: [green("\u2714")],
74
+ warning: [yellow("\u26A0")],
75
+ error: [red("\u2717")]
76
+ };
@@ -0,0 +1,3 @@
1
+ import type { OutputParser, Tool } from "../types";
2
+ export declare const eslint: Tool;
3
+ export declare const parseOuptut: OutputParser;
@@ -0,0 +1,44 @@
1
+ import { isBinInstalled, execAndParse } from "../utils.mjs";
2
+ const bin = "node_modules/.bin/eslint";
3
+ const args = [
4
+ ".",
5
+ "--ext",
6
+ ".js,.ts,.jsx,.tsx,.mjs,.mts,.cjs,.cts,.vue",
7
+ "--format",
8
+ "compact",
9
+ "--max-warnings",
10
+ "0"
11
+ ];
12
+ export const eslint = {
13
+ name: "ESLint",
14
+ isInstalled: (root) => isBinInstalled(bin, root),
15
+ check: (root) => execAndParse(root, bin, args, parseOuptut),
16
+ fix: (root) => execAndParse(root, bin, [...args, "--fix"], parseOuptut)
17
+ };
18
+ export const parseOuptut = ({ code, stdout, stderr }) => {
19
+ if (code === 0)
20
+ return { type: "success" };
21
+ const problems = `${stdout}
22
+ ${stderr}`.split(/\r?\n/).reduce((acc, line) => {
23
+ const match = /^(.*?): line ([0-9]+), col ([0-9]+), (\S+) - (.*?) \((\S*?)\)$/.exec(
24
+ line
25
+ );
26
+ if (match) {
27
+ acc.push({
28
+ file: match[1],
29
+ kind: match[4] === "Warning" ? "warning" : "error",
30
+ message: match[5],
31
+ location: {
32
+ line: parseInt(match[2], 10),
33
+ column: parseInt(match[3], 10)
34
+ },
35
+ rule: match[6]
36
+ });
37
+ }
38
+ return acc;
39
+ }, []);
40
+ return {
41
+ type: problems.some((problem) => problem.kind === "error") ? "error" : "warning",
42
+ problems
43
+ };
44
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,38 @@
1
+ import { describe, it, expect } from "bun:test";
2
+ import { parseOuptut } from "./eslint.mjs";
3
+ describe("ESLint", () => {
4
+ it("should properly parse output", async () => {
5
+ const stdout = `/path/to/check/demo/test.ts: line 1, col 7, Warning - 'test' is assigned a value but never used. (@typescript-eslint/no-unused-vars)
6
+ /path/to/check/demo/test.ts: line 5, col 7, Error - 'variable' is assigned a value but never used. (@typescript-eslint/no-unused-vars)
7
+
8
+ 4 problems
9
+ `;
10
+ const stderr = "";
11
+ const code = 1;
12
+ expect(parseOuptut({ code, stdout, stderr })).toEqual({
13
+ type: "error",
14
+ problems: [
15
+ {
16
+ file: "/path/to/check/demo/test.ts",
17
+ message: "'test' is assigned a value but never used.",
18
+ kind: "warning",
19
+ location: {
20
+ line: 1,
21
+ column: 7
22
+ },
23
+ rule: "@typescript-eslint/no-unused-vars"
24
+ },
25
+ {
26
+ file: "/path/to/check/demo/test.ts",
27
+ message: "'variable' is assigned a value but never used.",
28
+ kind: "error",
29
+ location: {
30
+ line: 5,
31
+ column: 7
32
+ },
33
+ rule: "@typescript-eslint/no-unused-vars"
34
+ }
35
+ ]
36
+ });
37
+ });
38
+ });
@@ -0,0 +1,2 @@
1
+ import type { Tool } from "../types";
2
+ export declare const ALL_TOOLS: Tool[];
@@ -0,0 +1,5 @@
1
+ import { eslint } from "./eslint.mjs";
2
+ import { prettier } from "./prettier.mjs";
3
+ import { typescript } from "./typescript.mjs";
4
+ import { publint } from "./publint.mjs";
5
+ export const ALL_TOOLS = [prettier, typescript, eslint, publint];
@@ -0,0 +1,3 @@
1
+ import type { Tool, OutputParser } from "../types";
2
+ export declare const prettier: Tool;
3
+ export declare const parseOuptut: OutputParser;
@@ -0,0 +1,25 @@
1
+ import { execAndParse, isBinInstalled } from "../utils.mjs";
2
+ const bin = "node_modules/.bin/prettier";
3
+ const checkArgs = [".", "--list-different"];
4
+ const fixArgs = [".", "--fix"];
5
+ export const prettier = {
6
+ name: "Prettier",
7
+ isInstalled: (root) => isBinInstalled(bin, root),
8
+ check: (root) => execAndParse(root, bin, checkArgs, parseOuptut),
9
+ fix: (root) => execAndParse(root, bin, fixArgs, parseOuptut)
10
+ };
11
+ export const parseOuptut = ({ code, stdout }) => {
12
+ if (code === 0)
13
+ return { type: "success" };
14
+ const problems = stdout.trim().split(/\r?\n/).map(
15
+ (line) => ({
16
+ file: line.trim(),
17
+ kind: "warning",
18
+ message: "Not formatted."
19
+ })
20
+ );
21
+ return {
22
+ type: "warning",
23
+ problems
24
+ };
25
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,26 @@
1
+ import { describe, it, expect } from "bun:test";
2
+ import { parseOuptut } from "./prettier.mjs";
3
+ describe("Prettier", () => {
4
+ it("should properly parse output", async () => {
5
+ const stdout = `target/.rustc_info.json
6
+ test.ts
7
+ `;
8
+ const stderr = "";
9
+ const code = 1;
10
+ expect(parseOuptut({ code, stdout, stderr })).toEqual({
11
+ type: "warning",
12
+ problems: [
13
+ {
14
+ file: "target/.rustc_info.json",
15
+ message: "Not formatted.",
16
+ kind: "warning"
17
+ },
18
+ {
19
+ file: "test.ts",
20
+ message: "Not formatted.",
21
+ kind: "warning"
22
+ }
23
+ ]
24
+ });
25
+ });
26
+ });
@@ -0,0 +1,3 @@
1
+ import type { OutputParser, Tool } from "../types";
2
+ export declare const publint: Tool;
3
+ export declare const parseOuptut: OutputParser;
@@ -0,0 +1,32 @@
1
+ import { isBinInstalled, execAndParse } from "../utils.mjs";
2
+ const bin = "node_modules/.bin/publint";
3
+ const args = [];
4
+ export const publint = {
5
+ name: "Publint",
6
+ isInstalled: (root) => isBinInstalled(bin, root),
7
+ check: (root) => execAndParse(root, bin, args, parseOuptut)
8
+ };
9
+ export const parseOuptut = ({ code, stdout, stderr }) => {
10
+ if (code === 0)
11
+ return { type: "success" };
12
+ let kind = "warning";
13
+ const problems = stdout.split(/\r?\n/).reduce((acc, line) => {
14
+ if (line.includes("Errors:")) {
15
+ kind = "error";
16
+ return acc;
17
+ }
18
+ const match = /^[0-9]+\.\s?(.*)$/.exec(line);
19
+ if (match == null)
20
+ return acc;
21
+ acc.push({
22
+ kind,
23
+ message: match[1],
24
+ file: "package.json"
25
+ });
26
+ return acc;
27
+ }, []);
28
+ return {
29
+ type: kind,
30
+ problems
31
+ };
32
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,36 @@
1
+ import { describe, it, expect } from "bun:test";
2
+ import { parseOuptut } from "./publint.mjs";
3
+ describe("Publint", () => {
4
+ it("should properly parse output", async () => {
5
+ const stdout = `@aklinker1/check lint results:
6
+ Suggestions:
7
+ 1. Consider being better lolz.
8
+ Warnings:
9
+ 1. pkg.exports["."].import types is not exported. Consider adding pkg.exports["."].import.types: "./dist/index.d.ts" to be compatible with TypeScript's "moduleResolution": "bundler" compiler option.
10
+ Errors:
11
+ 1. pkg.module is ./dist/index.cjs but the file does not exist.
12
+ `;
13
+ const stderr = "";
14
+ const code = 1;
15
+ expect(parseOuptut({ code, stdout, stderr })).toEqual({
16
+ type: "error",
17
+ problems: [
18
+ {
19
+ file: "package.json",
20
+ message: "Consider being better lolz.",
21
+ kind: "warning"
22
+ },
23
+ {
24
+ file: "package.json",
25
+ message: `pkg.exports["."].import types is not exported. Consider adding pkg.exports["."].import.types: "./dist/index.d.ts" to be compatible with TypeScript's "moduleResolution": "bundler" compiler option.`,
26
+ kind: "warning"
27
+ },
28
+ {
29
+ file: "package.json",
30
+ message: "pkg.module is ./dist/index.cjs but the file does not exist.",
31
+ kind: "error"
32
+ }
33
+ ]
34
+ });
35
+ });
36
+ });
@@ -0,0 +1,3 @@
1
+ import type { Tool, OutputParser } from "../types";
2
+ export declare const typescript: Tool;
3
+ export declare const parseOuptut: OutputParser;
@@ -0,0 +1,34 @@
1
+ import { execAndParse, isBinInstalled } from "../utils.mjs";
2
+ const bin = "node_modules/.bin/tsc";
3
+ const checkArgs = ["--noEmit", "--pretty", "false"];
4
+ export const typescript = {
5
+ name: "TypeScript",
6
+ isInstalled: (root) => isBinInstalled(bin, root),
7
+ check: (root) => execAndParse(root, bin, checkArgs, parseOuptut)
8
+ };
9
+ export const parseOuptut = ({ code, stdout }) => {
10
+ if (code === 0)
11
+ return { type: "success" };
12
+ const problems = stdout.split(/\r?\n/).reduce((acc, line) => {
13
+ const match = /^(\S+?)\(([0-9]+),([0-9]+)\): \w+? (TS[0-9]+): (.*)$/.exec(
14
+ line
15
+ );
16
+ if (match) {
17
+ acc.push({
18
+ file: match[1],
19
+ kind: "error",
20
+ message: match[5],
21
+ location: {
22
+ line: parseInt(match[2], 10),
23
+ column: parseInt(match[3], 10)
24
+ },
25
+ rule: match[4]
26
+ });
27
+ }
28
+ return acc;
29
+ }, []);
30
+ return {
31
+ type: "error",
32
+ problems
33
+ };
34
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,36 @@
1
+ import { describe, it, expect } from "bun:test";
2
+ import { parseOuptut } from "./typescript.mjs";
3
+ describe("TypeScript", () => {
4
+ it("should properly parse output", async () => {
5
+ const stdout = `test.ts(1,19): error TS2355: A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value.
6
+ test.ts(5,24): error TS7006: Parameter 'a' implicitly has an 'any' type.
7
+ `;
8
+ const stderr = "";
9
+ const code = 1;
10
+ expect(parseOuptut({ code, stdout, stderr })).toEqual({
11
+ type: "error",
12
+ problems: [
13
+ {
14
+ file: "test.ts",
15
+ message: "A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value.",
16
+ kind: "error",
17
+ location: {
18
+ line: 1,
19
+ column: 19
20
+ },
21
+ rule: "TS2355"
22
+ },
23
+ {
24
+ file: "test.ts",
25
+ message: "Parameter 'a' implicitly has an 'any' type.",
26
+ kind: "error",
27
+ location: {
28
+ line: 5,
29
+ column: 24
30
+ },
31
+ rule: "TS7006"
32
+ }
33
+ ]
34
+ });
35
+ });
36
+ });
@@ -0,0 +1,61 @@
1
+ export interface CheckOptions {
2
+ /**
3
+ * Set to true to fix problems that can be automatically fixed.
4
+ */
5
+ fix?: boolean;
6
+ /**
7
+ * Directory to run commands in.
8
+ */
9
+ root?: string;
10
+ /**
11
+ * Set to true to enable debug logs.
12
+ */
13
+ debug?: boolean;
14
+ }
15
+ export interface Tool {
16
+ /**
17
+ * Name of tool shown in the console output.
18
+ */
19
+ name: string;
20
+ /**
21
+ * Check if the tool is installed.
22
+ */
23
+ isInstalled: (root: string | undefined) => Promise<boolean>;
24
+ /**
25
+ * Run the tool, only checking for problems.
26
+ */
27
+ check: (root: string | undefined) => Promise<Output>;
28
+ /**
29
+ * Run the tool, but fix problems if possible. If the tool doesn't support fixing problems, `check` will be called instead.
30
+ */
31
+ fix?: (root: string | undefined) => Promise<Output>;
32
+ }
33
+ export type Output = OutputSuccess | OutputWarning | OutputError;
34
+ export interface OutputSuccess {
35
+ type: "success";
36
+ }
37
+ export interface OutputWarning {
38
+ type: "warning";
39
+ problems: Problem[];
40
+ }
41
+ export interface OutputError {
42
+ type: "error";
43
+ problems: Problem[];
44
+ }
45
+ export interface Problem {
46
+ location?: CodeLocation;
47
+ message: string;
48
+ file: string;
49
+ kind: ProblemKind;
50
+ rule?: string;
51
+ }
52
+ export interface CodeLocation {
53
+ line: number;
54
+ column: number;
55
+ }
56
+ export type ProblemKind = "warning" | "error";
57
+ export type OutputParser = (data: {
58
+ code: number;
59
+ stdout: string;
60
+ stderr: string;
61
+ }) => Output;
package/dist/types.mjs ADDED
File without changes
@@ -0,0 +1,12 @@
1
+ import type { OutputParser, Output } from "./types";
2
+ export declare function isBinInstalled(bin: string, root?: string): Promise<boolean>;
3
+ export declare function execAndParse(root: string | undefined, bin: string, args: string[], parser: OutputParser): Promise<Output>;
4
+ export declare function isDebug(): boolean;
5
+ export declare const bold: (str: string) => string;
6
+ export declare const dim: (str: string) => string;
7
+ export declare const red: (str: string) => string;
8
+ export declare const green: (str: string) => string;
9
+ export declare const yellow: (str: string) => string;
10
+ export declare const cyan: (str: string) => string;
11
+ export declare function humanMs(ms: number): string;
12
+ export declare function debug(message: string): void;
package/dist/utils.mjs ADDED
@@ -0,0 +1,64 @@
1
+ import { spawn } from "node:child_process";
2
+ import { stat } from "fs/promises";
3
+ import { resolve } from "node:path";
4
+ function resolveRoot(root, ...path) {
5
+ return root != null ? resolve(root, ...path) : resolve(...path);
6
+ }
7
+ export async function isBinInstalled(bin, root) {
8
+ try {
9
+ const binPath = resolveRoot(root, bin);
10
+ if (isDebug())
11
+ debug(`Checking if binary exists: ${binPath}`);
12
+ await stat(resolveRoot(root, bin));
13
+ return true;
14
+ } catch (err) {
15
+ return false;
16
+ }
17
+ }
18
+ function exec(cmd, args, opts) {
19
+ return new Promise((resolve2, reject) => {
20
+ const child = spawn(cmd, args, opts);
21
+ let stderr = "";
22
+ let stdout = "";
23
+ child.stdout.on("data", (data) => {
24
+ stdout += data.toString();
25
+ });
26
+ child.stderr.on("data", (data) => {
27
+ stderr += data.toString();
28
+ });
29
+ child.on("error", (error) => {
30
+ reject(error);
31
+ });
32
+ child.on("close", (exitCode) => {
33
+ resolve2({ stderr, stdout, exitCode });
34
+ });
35
+ });
36
+ }
37
+ export async function execAndParse(root, bin, args, parser) {
38
+ const res = await exec(resolveRoot(root, bin), args, { cwd: root });
39
+ if (res.exitCode == null)
40
+ throw Error("Exit code was null");
41
+ return parser({
42
+ code: res.exitCode,
43
+ stderr: res.stderr,
44
+ stdout: res.stdout
45
+ });
46
+ }
47
+ export function isDebug() {
48
+ return process.env.DEBUG === "true" || process.env.DEBUG === "1";
49
+ }
50
+ export const bold = (str) => `\x1B[1m${str}\x1B[0m`;
51
+ export const dim = (str) => `\x1B[2m${str}\x1B[0m`;
52
+ export const red = (str) => `\x1B[31m${str}\x1B[0m`;
53
+ export const green = (str) => `\x1B[32m${str}\x1B[0m`;
54
+ export const yellow = (str) => `\x1B[33m${str}\x1B[0m`;
55
+ export const cyan = (str) => `\x1B[36m${str}\x1B[0m`;
56
+ export function humanMs(ms) {
57
+ const minutes = Math.floor(ms / 6e4);
58
+ const seconds = (ms % 6e4 / 1e3).toFixed(minutes > 0 ? 0 : 3);
59
+ return `${minutes > 0 ? `${minutes}m ` : ""}${seconds}s`;
60
+ }
61
+ export function debug(message) {
62
+ if (isDebug())
63
+ console.debug(dim("\u2699 " + message));
64
+ }
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@aklinker1/check",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": {
7
+ "types": "./dist/index.d.ts",
8
+ "import": "./dist/index.mjs"
9
+ }
10
+ },
11
+ "module": "./dist/index.mjs",
12
+ "types": "./dist/index.d.ts",
13
+ "files": ["dist"],
14
+ "bin": {
15
+ "check": "bin/check.mjs"
16
+ },
17
+ "scripts": {
18
+ "build": "bunx unbuild",
19
+ "check": "bun src/cli.ts",
20
+ "prepublish": "bun build"
21
+ },
22
+ "dependencies": {
23
+ "@antfu/utils": "^0.7.7",
24
+ "citty": "^0.1.6"
25
+ },
26
+ "devDependencies": {
27
+ "@types/bun": "latest",
28
+ "publint": "^0.2.7",
29
+ "unbuild": "latest"
30
+ },
31
+ "peerDependencies": {
32
+ "typescript": "^5.0.0"
33
+ },
34
+ "unbuild": {
35
+ "entries": [
36
+ {
37
+ "builder": "mkdist",
38
+ "input": "./src/",
39
+ "outDir": "./dist"
40
+ }
41
+ ],
42
+ "declaration": true
43
+ }
44
+ }