Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/bot-cli/bin/bot.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/usr/bin/env node

/**
* CLI entry point
*/

import { program } from "../src/index.js";

program.parse(process.argv);
61 changes: 61 additions & 0 deletions packages/bot-cli/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
{
"name": "@tego/bot-cli",
"version": "0.2.2",
"description": "CLI wrapper for @tego/botjs",
"type": "module",
"bin": {
"bot": "./dist/bin/bot.mjs"
},
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"exports": {
".": {
"import": "./dist/src/index.js",
"types": "./dist/src/index.d.ts"
}
},
"scripts": {
"build": "tsdown",
"dev": "tsdown --watch",
"gen:api": "tsx ./tools/gen-api.ts",
"gen:commands": "tsx ./tools/gen-commands.ts",
"gen": "pnpm gen:api && pnpm gen:commands",
"test": "vitest run",
"test:watch": "vitest"
},
"dependencies": {
"@tego/botjs": "workspace:*",
"commander": "^13.0.0"
},
"devDependencies": {
"@types/node": "^24.5.2",
"ts-morph": "^27.0.0",
"tsdown": "^0.16.6",
"tsx": "^4.20.6",
"typescript": "^5.9.2",
"vitest": "^4.0.9"
},
"files": [
"dist",
"readme.md",
"package.json"
],
"repository": {
"type": "git",
"url": "https://github.com/tegojs/bot.git",
"directory": "packages/bot-cli"
},
"homepage": "https://github.com/tegojs/bot#readme",
"bugs": {
"url": "https://github.com/tegojs/bot/issues"
},
"license": "MIT",
"author": {
"name": "sealday",
"email": "sealday@gmail.com",
"url": "https://github.com/sealday"
},
"engines": {
"node": ">= 20"
}
}
53 changes: 53 additions & 0 deletions packages/bot-cli/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# @tego/bot-cli

CLI wrapper for @tego/botjs.

## Installation

```bash
# Install in the workspace
pnpm install

# Build the package
pnpm --filter @tego/bot-cli build
```

## Usage

### Generic invocation

```bash
bot call moveMouse --json '[100,200]'
bot call mouseClick --json '["left", true]'
bot call captureScreen --json '[]' --out screenshot.png
```

### Args input modes

```bash
bot call moveMouse --file args.json
bot call moveMouse --stdin
```

### Dry-run validation

```bash
bot call moveMouse --json '[100,200]' --dry-run
```

### Doctor command

```bash
bot doctor
bot doctor --json-output
```

## Output

- Default output is human-readable.
- Use `--json` to emit machine JSON output.
Copy link

Copilot AI Jan 28, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The documentation states to use --json to emit machine JSON output, but the correct flag is --json-output as seen in the CLI implementation (src/index.ts line 22) and the generated commands. This inconsistency will confuse users.

Copilot uses AI. Check for mistakes.
- For Buffer results, use `--out` to write to file.

## License

MIT
52 changes: 52 additions & 0 deletions packages/bot-cli/src/commands/call.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import * as fs from "node:fs/promises";
import { stdin as stdinStream } from "node:process";
import { invokeExport } from "./invoke.js";

export interface CallOptions {
json?: string;
file?: string;
stdin?: boolean;
out?: string;
jsonOutput?: boolean;
validate?: boolean;
dryRun?: boolean;
}

async function readStdin(): Promise<string> {
const chunks: Buffer[] = [];
for await (const chunk of stdinStream) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
}
return Buffer.concat(chunks).toString("utf8");
}

async function loadArgs(options: CallOptions): Promise<unknown> {
if (options.json) {
return JSON.parse(options.json);
}
if (options.file) {
const contents = await fs.readFile(options.file, "utf8");
return JSON.parse(contents);
}
if (options.stdin) {
const contents = await readStdin();
return JSON.parse(contents);
}
return [];
}

export async function callCommand(
exportName: string,
options: CallOptions,
): Promise<void> {
const args = await loadArgs(options);
const normalizedArgs = Array.isArray(args) ? args : [args];
if (options.dryRun) {
await invokeExport(exportName, normalizedArgs, {
...options,
out: undefined,
});
return;
}
await invokeExport(exportName, normalizedArgs, options);
}
20 changes: 20 additions & 0 deletions packages/bot-cli/src/commands/doctor.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { describe, expect, it, vi } from "vitest";
import { doctorCommand } from "./doctor.js";

describe("doctorCommand", () => {
it("prints messages for macOS", async () => {
const platformSpy = vi
.spyOn(process, "platform", "get")
.mockReturnValue("darwin");
const writeSpy = vi
.spyOn(process.stdout, "write")
.mockImplementation(() => true);

await doctorCommand(true);

const output = writeSpy.mock.calls.map((call) => call[0]).join("");
expect(output).toContain("Screen Recording");
platformSpy.mockRestore();
writeSpy.mockRestore();
});
});
40 changes: 40 additions & 0 deletions packages/bot-cli/src/commands/doctor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { platform } from "node:os";

interface DoctorResult {
ok: boolean;
platform: string;
messages: string[];
}

export async function doctorCommand(jsonOutput: boolean): Promise<void> {
const result: DoctorResult = {
ok: true,
platform: platform(),
messages: [],
};

if (result.platform === "darwin") {
result.messages.push(
"macOS permissions: ensure Screen Recording access is granted (System Settings > Privacy & Security > Screen Recording).",
);
} else if (result.platform === "win32") {
result.messages.push(
"Windows: no additional permissions typically required.",
);
} else if (result.platform === "linux") {
result.messages.push(
"Linux: ensure a display server is available (X11/Wayland).",
);
} else {
result.messages.push(`Platform '${result.platform}' is untested.`);
}

if (jsonOutput) {
process.stdout.write(`${JSON.stringify(result)}\n`);
return;
}

for (const message of result.messages) {
process.stdout.write(`${message}\n`);
}
}
151 changes: 151 additions & 0 deletions packages/bot-cli/src/commands/invoke.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import * as fs from "node:fs/promises";
import * as bot from "@tego/botjs";
import { validateArgs } from "./validate.js";

export interface InvokeOptions {
out?: string;
jsonOutput?: boolean;
validate?: boolean;
dryRun?: boolean;
}

function isBuffer(value: unknown): value is Buffer {
return Buffer.isBuffer(value);
}

function extractBufferField(
value: unknown,
): { buffer: Buffer; remaining?: Record<string, unknown> } | null {
if (!value || typeof value !== "object") {
return null;
}
const record = value as Record<string, unknown>;
if (isBuffer(record.image)) {
const { image, ...rest } = record;
return { buffer: image, remaining: rest };
}
if (isBuffer(record.buffer)) {
const { buffer, ...rest } = record;
return { buffer, remaining: rest };
}
return null;
}

function isPromise<T>(value: T | Promise<T>): value is Promise<T> {
return Boolean(value) && typeof (value as Promise<T>).then === "function";
}

async function writeResult(
result: unknown,
options: InvokeOptions,
): Promise<void> {
if (isBuffer(result)) {
if (!options.out) {
throw new Error("Buffer result requires --out <path> to write file.");
}
await fs.writeFile(options.out, result);
if (options.jsonOutput) {
process.stdout.write(
JSON.stringify({ out: options.out, bytes: result.length }),
);
} else {
process.stdout.write(`Wrote ${result.length} bytes to ${options.out}\n`);
}
return;
}

const extracted = extractBufferField(result);
if (options.out) {
if (!extracted) {
throw new Error(
"--out was provided but result did not contain a Buffer.",
);
}
await fs.writeFile(options.out, extracted.buffer);
if (options.jsonOutput) {
const payload = {
out: options.out,
bytes: extracted.buffer.length,
...(extracted.remaining && Object.keys(extracted.remaining).length > 0
? { result: extracted.remaining }
: {}),
};
process.stdout.write(`${JSON.stringify(payload)}\n`);
} else {
process.stdout.write(
`Wrote ${extracted.buffer.length} bytes to ${options.out}\n`,
);
}
return;
}

if (options.jsonOutput) {
process.stdout.write(`${JSON.stringify(result)}\n`);
return;
}

if (typeof result === "undefined") {
process.stdout.write("OK\n");
return;
}

if (typeof result === "string") {
process.stdout.write(`${result}\n`);
return;
}

process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
}

export async function invokeExport(
exportName: string,
args: unknown[],
options: InvokeOptions,
): Promise<void> {
const fn = (bot as Record<string, unknown>)[exportName];
if (typeof fn !== "function") {
const names = Object.keys(bot).sort();
const matches = names.filter((name) =>
name.toLowerCase().includes(exportName.toLowerCase()),
);
const suffix =
matches.length > 0 ? `\nClosest matches: ${matches.join(", ")}` : "";
throw new Error(`Export '${exportName}' is not a function.${suffix}`);
}

const minArgs = fn.length;
const shouldValidate = options.validate !== false;
await validateArgs(exportName, args, shouldValidate);
if (
shouldValidate &&
args.length === 1 &&
args[0] &&
typeof args[0] === "object" &&
!Array.isArray(args[0]) &&
minArgs > 1
) {
throw new Error(
`Argument for '${exportName}' should be an array when calling functions with ${minArgs} parameters.`,
);
}

if (options.dryRun) {
if (options.jsonOutput) {
process.stdout.write(
`${JSON.stringify({ ok: true, exportName, args, dryRun: true })}\n`,
);
} else {
process.stdout.write(`OK (dry-run): ${exportName}\n`);
}
return;
}

let result: unknown;
result = (fn as (...values: unknown[]) => unknown)(...args);

if (isPromise(result)) {
result = await result;
}

await writeResult(result, options);
}
Loading
Loading