diff --git a/apps/cli/package.json b/apps/cli/package.json new file mode 100644 index 000000000..a51130e24 --- /dev/null +++ b/apps/cli/package.json @@ -0,0 +1,33 @@ +{ + "name": "@follow/cli", + "type": "module", + "version": "0.1.0", + "private": true, + "description": "Folo CLI for AI agents and power users", + "bin": { + "folo": "./dist/index.js" + }, + "files": [ + "dist", + "skill.md" + ], + "scripts": { + "build": "tsup --config tsup.config.ts && chmod +x dist/index.js", + "dev": "tsx src/index.ts", + "start": "node dist/index.js", + "test": "pnpm run build && vitest run", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@follow-app/client-sdk": "catalog:", + "commander": "14.0.1", + "pathe": "2.0.3" + }, + "devDependencies": { + "@follow/configs": "workspace:*", + "@types/node": "25.2.3", + "tsup": "8.5.0", + "tsx": "4.21.0", + "typescript": "catalog:" + } +} diff --git a/apps/cli/skill.md b/apps/cli/skill.md new file mode 100644 index 000000000..ca3eb16db --- /dev/null +++ b/apps/cli/skill.md @@ -0,0 +1,172 @@ +# Folo CLI Skill + +## Trigger Conditions + +Use this skill when a user asks to: + +- Manage RSS subscriptions +- Browse timeline entries +- Read entry details or readability content +- Mark entries as read/unread +- Search feeds/lists or trending sources +- Import/export OPML +- Check unread counts + +## Preconditions + +1. Folo CLI is installed and executable as `folo`. +2. Authentication is configured: + - `folo auth login --token ` + - or set `FOLO_TOKEN=` + +## Output Contract + +Default output is JSON with a stable envelope: + +```json +{ + "ok": true, + "data": {}, + "error": null +} +``` + +Errors return: + +```json +{ + "ok": false, + "data": null, + "error": { + "code": "UNAUTHORIZED", + "message": "Token is invalid or expired." + } +} +``` + +You can switch output mode: + +- `--format json` (default) +- `--format table` +- `--format plain` + +## Core Workflows + +### 1. Timeline Reading + +1. Fetch timeline: + - `folo timeline --limit 10` +2. Get entry detail: + - `folo entry get ` +3. Get readability content: + - `folo entry read ` + +### 2. Subscription Management + +1. Discover: + - `folo search discover ` +2. Add subscription: + - `folo subscription add --feed ` + - or `folo subscription add --list ` +3. List subscriptions: + - `folo subscription list` + +### 3. Unread Processing + +1. Check unread total: + - `folo unread count` +2. List unread subscriptions: + - `folo unread list` +3. Read unread entries: + - `folo timeline --unread-only --limit 20` +4. Mark read: + - `folo entry mark-read ` + - or batch: `folo entry mark-all-read --view articles` + +### 4. Collection Operations + +- Add: `folo collection add ` +- Remove: `folo collection remove ` +- List: `folo collection list --limit 20` + +### 5. OPML Import / Export + +- Export: + - `folo opml export --output backup.opml` +- Import: + - `folo opml import feeds.opml` + +## Pagination Pattern + +`folo timeline` returns: + +- `entries` +- `nextCursor` +- `hasNext` + +Loop until `hasNext` is `false`: + +1. `folo timeline --limit 20` +2. Read `nextCursor` +3. `folo timeline --limit 20 --cursor ` +4. Repeat + +## Command Reference + +- `folo auth login --token ` +- `folo auth logout` +- `folo auth whoami` + +- `folo timeline [--view ] [--limit ] [--unread-only] [--cursor ]` +- `folo timeline --feed [--limit ] [--cursor ]` +- `folo timeline --list [--limit ] [--cursor ]` +- `folo timeline --category [--view ] [--limit ]` + +- `folo subscription list [--view ] [--category ]` +- `folo subscription add --feed [--category ] [--view ] [--private]` +- `folo subscription add --list [--category ] [--view ]` +- `folo subscription remove [--target feed|list|url]` +- `folo subscription update [--target feed|list] [--category ] [--title ] [--view <type>] [--private|--public]` + +- `folo entry get <entryId>` +- `folo entry read <entryId>` +- `folo entry mark-read <entryId>` +- `folo entry mark-unread <entryId>` +- `folo entry mark-all-read [--feed <feedId>] [--list <listId>] [--view <type>]` + +- `folo feed get <feedId|feedUrl>` +- `folo feed refresh <feedId>` +- `folo feed analytics <feedId>` + +- `folo list ls` +- `folo list get <listId>` +- `folo list create --title <title> [--description <desc>] [--view <type>] [--fee <n>]` +- `folo list update <listId> [--title <title>] [--description <desc>] [--view <type>] [--fee <n>]` +- `folo list delete <listId>` +- `folo list add-feed <listId> --feed <feedId>` +- `folo list remove-feed <listId> --feed <feedId>` + +- `folo search discover <keyword> [--type feeds|lists]` +- `folo search rsshub <keyword> [--lang <lang>]` +- `folo search trending [--range 1d|3d|7d|30d] [--view <type>] [--limit <n>] [--language eng|cmn] [--category <keyword>]` + +- `folo collection list [--limit <n>] [--cursor <datetime>]` +- `folo collection add <entryId> [--view <type>]` +- `folo collection remove <entryId>` + +- `folo opml export [--output <file>]` +- `folo opml import <file> [--items <url1,url2,...>]` + +- `folo unread count` +- `folo unread list [--view <type>]` + +## Error Recovery + +- `UNAUTHORIZED` + - Re-login: `folo auth login --token <token>` + - Or set `FOLO_TOKEN` +- `HTTP_4xx` / `HTTP_5xx` + - Retry with `--verbose` for request details + - Verify `--api-url` if using non-default endpoint +- `INVALID_ARGUMENT` + - Run `folo <command> --help` to inspect accepted options diff --git a/apps/cli/src/args.test.ts b/apps/cli/src/args.test.ts new file mode 100644 index 000000000..72a926b9e --- /dev/null +++ b/apps/cli/src/args.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from "vitest" + +import { parseFormat, parseISODate, parseNonNegativeInt, parsePositiveInt, parseView } from "./args" + +describe("args parsers", () => { + it("parses named view values", () => { + expect(parseView("articles")).toBe(0) + expect(parseView("social")).toBe(1) + expect(parseView("pictures")).toBe(2) + expect(parseView("videos")).toBe(3) + expect(parseView("audio")).toBe(4) + expect(parseView("notifications")).toBe(5) + }) + + it("parses numeric view values", () => { + expect(parseView("0")).toBe(0) + expect(parseView("5")).toBe(5) + }) + + it("throws for invalid view values", () => { + expect(() => parseView("foo")).toThrowError(/Invalid view/) + expect(() => parseView("6")).toThrowError(/Invalid view/) + }) + + it("parses positive integers", () => { + expect(parsePositiveInt("1")).toBe(1) + expect(parsePositiveInt("99")).toBe(99) + }) + + it("throws for non-positive integers", () => { + expect(() => parsePositiveInt("0")).toThrowError(/positive integer/) + expect(() => parsePositiveInt("-1")).toThrowError(/positive integer/) + }) + + it("parses non-negative integers", () => { + expect(parseNonNegativeInt("0")).toBe(0) + expect(parseNonNegativeInt("3")).toBe(3) + }) + + it("throws for negative integers", () => { + expect(() => parseNonNegativeInt("-1")).toThrowError(/non-negative integer/) + }) + + it("parses ISO datetime", () => { + expect(parseISODate("2026-02-25T10:30:00Z")).toBe("2026-02-25T10:30:00.000Z") + }) + + it("throws for invalid datetime", () => { + expect(() => parseISODate("not-a-date")).toThrowError(/Invalid datetime/) + }) + + it("parses output format", () => { + expect(parseFormat("json")).toBe("json") + expect(parseFormat("table")).toBe("table") + expect(parseFormat("plain")).toBe("plain") + }) + + it("throws for invalid output format", () => { + expect(() => parseFormat("yaml")).toThrowError(/Invalid format/) + }) +}) diff --git a/apps/cli/src/args.ts b/apps/cli/src/args.ts new file mode 100644 index 000000000..16c366e2b --- /dev/null +++ b/apps/cli/src/args.ts @@ -0,0 +1,66 @@ +import type { OutputFormat } from "./output" + +const viewMap: Readonly<Record<string, number>> = { + article: 0, + articles: 0, + social: 1, + socialmedia: 1, + picture: 2, + pictures: 2, + video: 3, + videos: 3, + audio: 4, + notification: 5, + notifications: 5, +} + +export const viewHelp = + "articles(0) | social(1) | pictures(2) | videos(3) | audio(4) | notifications(5)" + +export const parseView = (value: string): number => { + const normalized = value.trim().toLowerCase() + if (/^\d+$/.test(normalized)) { + const parsed = Number.parseInt(normalized, 10) + if (parsed >= 0 && parsed <= 5) { + return parsed + } + } + + const mapped = viewMap[normalized] + if (mapped !== undefined) { + return mapped + } + + throw new Error(`Invalid view "${value}". Use ${viewHelp}.`) +} + +export const parsePositiveInt = (value: string): number => { + const parsed = Number.parseInt(value, 10) + if (!Number.isInteger(parsed) || parsed <= 0) { + throw new Error(`Expected a positive integer, got "${value}".`) + } + return parsed +} + +export const parseNonNegativeInt = (value: string): number => { + const parsed = Number.parseInt(value, 10) + if (!Number.isInteger(parsed) || parsed < 0) { + throw new Error(`Expected a non-negative integer, got "${value}".`) + } + return parsed +} + +export const parseISODate = (value: string): string => { + const timestamp = Date.parse(value) + if (Number.isNaN(timestamp)) { + throw new TypeError(`Invalid datetime value "${value}".`) + } + return new Date(timestamp).toISOString() +} + +export const parseFormat = (value: string): OutputFormat => { + if (value === "json" || value === "table" || value === "plain") { + return value + } + throw new Error(`Invalid format "${value}". Use json, table, or plain.`) +} diff --git a/apps/cli/src/cli.e2e.test.ts b/apps/cli/src/cli.e2e.test.ts new file mode 100644 index 000000000..fb486d52f --- /dev/null +++ b/apps/cli/src/cli.e2e.test.ts @@ -0,0 +1,101 @@ +import type { ExecFileException } from "node:child_process" +import { execFile } from "node:child_process" +import { mkdtempSync } from "node:fs" +import { tmpdir } from "node:os" +import { promisify } from "node:util" + +import { resolve } from "pathe" +import { describe, expect, it } from "vitest" + +const execFileAsync = promisify(execFile) +const cliPath = resolve(process.cwd(), "dist/index.js") +const testToken = process.env.FOLO_TEST_TOKEN +const isolatedHome = mkdtempSync(resolve(tmpdir(), "folo-cli-test-")) + +type CLIExecution = { + code: number + stdout: string + stderr: string +} + +const runCLI = async (args: string[]): Promise<CLIExecution> => { + try { + const { stdout, stderr } = await execFileAsync("node", [cliPath, ...args], { + env: { + ...process.env, + HOME: isolatedHome, + USERPROFILE: isolatedHome, + FOLO_TOKEN: "", + }, + }) + + return { + code: 0, + stdout, + stderr, + } + } catch (error) { + const execError = error as ExecFileException & { + stdout?: string + stderr?: string + } + + return { + code: typeof execError.code === "number" ? execError.code : 1, + stdout: execError.stdout ?? "", + stderr: execError.stderr ?? "", + } + } +} + +describe("cli e2e", () => { + it("returns structured unauthorized error without token", async () => { + const result = await runCLI(["timeline", "--limit", "1"]) + expect(result.code).not.toBe(0) + + const payload = JSON.parse(result.stderr) as { + ok: boolean + data: null + error: { code: string; message: string } + } + expect(payload.ok).toBe(false) + expect(payload.data).toBeNull() + expect(payload.error.code).toBe("UNAUTHORIZED") + }) + + it.runIf(Boolean(testToken))("can fetch session with test token", async () => { + const result = await runCLI(["--token", testToken!, "auth", "whoami"]) + expect(result.code).toBe(0) + + const payload = JSON.parse(result.stdout) as { + ok: boolean + data: { + user: { id: string } + session: { id: string } + } + error: null + } + expect(payload.ok).toBe(true) + expect(payload.error).toBeNull() + expect(typeof payload.data.user.id).toBe("string") + expect(typeof payload.data.session.id).toBe("string") + }) + + it.runIf(Boolean(testToken))("can fetch timeline with test token", async () => { + const result = await runCLI(["--token", testToken!, "timeline", "--limit", "1"]) + expect(result.code).toBe(0) + + const payload = JSON.parse(result.stdout) as { + ok: boolean + data: { + entries: unknown[] + nextCursor: string | null + hasNext: boolean + } + error: null + } + expect(payload.ok).toBe(true) + expect(Array.isArray(payload.data.entries)).toBe(true) + expect(typeof payload.data.hasNext).toBe("boolean") + }) +}) diff --git a/apps/cli/src/client.ts b/apps/cli/src/client.ts new file mode 100644 index 000000000..2d74ba18d --- /dev/null +++ b/apps/cli/src/client.ts @@ -0,0 +1,113 @@ +import { FollowClient } from "@follow-app/client-sdk" +import type { Command } from "commander" + +import type { FoloCLIConfig } from "./config" +import { readConfig } from "./config" +import type { OutputFormat } from "./output" +import { CLIError } from "./output" + +export const defaultApiURL = "https://api.folo.is" + +const readString = (value: unknown): string | undefined => { + return typeof value === "string" && value.length > 0 ? value : undefined +} + +const normalizeToken = (token: string | undefined) => { + if (!token || !token.includes("%")) { + return token + } + + try { + return decodeURIComponent(token) + } catch { + return token + } +} + +export interface GlobalOptions { + format: OutputFormat + apiUrl?: string + token?: string + verbose: boolean +} + +export interface ResolvedGlobalOptions extends GlobalOptions { + apiUrl: string +} + +export interface CommandContext { + client: FollowClient + options: ResolvedGlobalOptions + config: FoloCLIConfig + token?: string +} + +export const getGlobalOptions = (command: Command): GlobalOptions => { + const options = command.optsWithGlobals() as Record<string, unknown> + + return { + format: + options.format === "table" || options.format === "plain" || options.format === "json" + ? options.format + : "json", + apiUrl: readString(options.apiUrl), + token: readString(options.token), + verbose: Boolean(options.verbose), + } +} + +const setupVerboseLogging = (client: FollowClient) => { + client.addRequestInterceptor((ctx) => { + const method = ctx.options.method || "GET" + console.error(`[request] ${method} ${ctx.url}`) + return ctx + }) + + client.addResponseInterceptor((ctx) => { + const method = ctx.options.method || "GET" + console.error(`[response] ${method} ${ctx.url} -> ${ctx.response.status}`) + return ctx.response + }) +} + +export const createCommandContext = async ( + command: Command, + requireAuth = true, +): Promise<CommandContext> => { + const globalOptions = getGlobalOptions(command) + const config = await readConfig() + const token = normalizeToken(globalOptions.token ?? process.env.FOLO_TOKEN ?? config.token) + const apiUrl = globalOptions.apiUrl ?? config.apiUrl ?? defaultApiURL + + if (requireAuth && !token) { + throw new CLIError( + "UNAUTHORIZED", + "Missing token. Run `folo auth login --token <token>` or set FOLO_TOKEN.", + ) + } + + const client = new FollowClient({ + baseURL: apiUrl, + }) + + if (token) { + client.setAuthToken(token) + client.setHeaders({ + Cookie: `__Secure-better-auth.session_token=${token}; better-auth.session_token=${token}`, + }) + } + + if (globalOptions.verbose) { + setupVerboseLogging(client) + } + + return { + client, + token, + config, + options: { + ...globalOptions, + apiUrl, + }, + } +} diff --git a/apps/cli/src/command.ts b/apps/cli/src/command.ts new file mode 100644 index 000000000..44d103844 --- /dev/null +++ b/apps/cli/src/command.ts @@ -0,0 +1,30 @@ +import type { Command } from "commander" + +import type { CommandContext } from "./client" +import { createCommandContext, getGlobalOptions } from "./client" +import { normalizeError, printFailure, printSuccess } from "./output" + +interface RunCommandOptions { + requireAuth?: boolean +} + +export const runCommand = async ( + command: Command, + handler: (context: CommandContext) => Promise<unknown>, + options: RunCommandOptions = {}, +) => { + const fallbackOptions = getGlobalOptions(command) + const requireAuth = options.requireAuth ?? true + + let context: CommandContext | null = null + try { + context = await createCommandContext(command, requireAuth) + const result = await handler(context) + printSuccess(context.options.format, result) + } catch (error) { + const format = context?.options.format ?? fallbackOptions.format + const verbose = context?.options.verbose ?? fallbackOptions.verbose + printFailure(format, normalizeError(error, verbose)) + process.exitCode = 1 + } +} diff --git a/apps/cli/src/commands/auth.ts b/apps/cli/src/commands/auth.ts new file mode 100644 index 000000000..c8503b8ec --- /dev/null +++ b/apps/cli/src/commands/auth.ts @@ -0,0 +1,87 @@ +import type { Command } from "commander" + +import { getGlobalOptions } from "../client" +import { runCommand } from "../command" +import { clearToken, getConfigPath, updateConfig } from "../config" +import { CLIError } from "../output" + +interface AuthLoginOptions { + token: string +} + +export const registerAuthCommand = (program: Command) => { + const authCommand = program.command("auth").description("Authentication commands") + + authCommand + .command("login") + .description("Save session token and verify authentication") + .option("--token <token>", "Session token from Folo") + .action(async function (this: Command, options: AuthLoginOptions) { + await runCommand( + this, + async ({ client, options: globalOptions }) => { + const token = options.token ?? getGlobalOptions(this).token + if (!token) { + throw new CLIError("INVALID_ARGUMENT", "Missing token. Use --token <token>.") + } + + client.setAuthToken(token) + const session = await client.api.auth.getSession() + + if (!session.user || !session.session) { + throw new CLIError("UNAUTHORIZED", "Token is invalid or expired.") + } + + await updateConfig({ + token, + apiUrl: globalOptions.apiUrl, + }) + + return { + message: "Login successful.", + configPath: getConfigPath(), + user: session.user, + } + }, + { requireAuth: false }, + ) + }) + + authCommand + .command("logout") + .description("Clear stored token") + .action(async function (this: Command) { + await runCommand( + this, + async () => { + await clearToken() + return { + message: "Logged out.", + configPath: getConfigPath(), + } + }, + { requireAuth: false }, + ) + }) + + authCommand + .command("whoami") + .description("Show current session user") + .action(async function (this: Command) { + await runCommand(this, async ({ client }) => { + const session = await client.api.auth.getSession() + if (!session.user || !session.session) { + throw new CLIError("UNAUTHORIZED", "Token is invalid or expired.") + } + + return { + user: session.user, + session: session.session, + role: session.role, + roleEndAt: session.roleEndAt ?? null, + feedSubscriptionLimit: session.feedSubscriptionLimit, + rsshubSubscriptionLimit: session.rsshubSubscriptionLimit, + } + }) + }) +} diff --git a/apps/cli/src/commands/collection.ts b/apps/cli/src/commands/collection.ts new file mode 100644 index 000000000..d91ff1807 --- /dev/null +++ b/apps/cli/src/commands/collection.ts @@ -0,0 +1,71 @@ +import type { EntryListRequest } from "@follow-app/client-sdk" +import type { Command } from "commander" + +import { parseISODate, parsePositiveInt, parseView, viewHelp } from "../args" +import { runCommand } from "../command" + +interface CollectionListOptions { + limit: number + cursor?: string +} + +interface CollectionAddOptions { + view?: number +} + +export const registerCollectionCommand = (program: Command) => { + const collectionCommand = program.command("collection").description("Manage collections") + + collectionCommand + .command("list") + .description("List collected entries") + .option("--limit <n>", "Number of entries to fetch", parsePositiveInt, 20) + .option("--cursor <datetime>", "Pagination cursor", parseISODate) + .action(async function (this: Command, options: CollectionListOptions) { + await runCommand(this, async ({ client }) => { + const request: EntryListRequest = { + isCollection: true, + limit: options.limit, + publishedAfter: options.cursor, + } + + const response = await client.api.entries.list(request) + const entries = response.data + const nextCursor = entries.at(-1)?.entries.publishedAt ?? null + + return { + entries, + nextCursor, + hasNext: Boolean(nextCursor) && entries.length >= options.limit, + } + }) + }) + + collectionCommand + .command("add") + .description("Add entry to collection") + .argument("<entryId>", "Entry ID") + .option("--view <type>", `View type: ${viewHelp}`, parseView) + .action(async function (this: Command, entryId: string, options: CollectionAddOptions) { + await runCommand(this, async ({ client }) => { + const response = await client.api.collections.post({ + entryId, + view: options.view, + }) + return response.data + }) + }) + + collectionCommand + .command("remove") + .description("Remove entry from collection") + .argument("<entryId>", "Entry ID") + .action(async function (this: Command, entryId: string) { + await runCommand(this, async ({ client }) => { + const response = await client.api.collections.delete({ + entryId, + }) + return response.data + }) + }) +} diff --git a/apps/cli/src/commands/entry.ts b/apps/cli/src/commands/entry.ts new file mode 100644 index 000000000..8cc10df38 --- /dev/null +++ b/apps/cli/src/commands/entry.ts @@ -0,0 +1,83 @@ +import type { MarkAllAsReadRequest } from "@follow-app/client-sdk" +import type { Command } from "commander" + +import { parseView, viewHelp } from "../args" +import { runCommand } from "../command" +import { CLIError } from "../output" + +interface MarkAllReadOptions { + feed?: string + list?: string + view?: number +} + +export const registerEntryCommand = (program: Command) => { + const entryCommand = program.command("entry").description("Read and update entries") + + entryCommand + .command("get") + .description("Get entry detail") + .argument("<entryId>", "Entry ID") + .action(async function (this: Command, entryId: string) { + await runCommand(this, async ({ client }) => { + const response = await client.api.entries.get({ id: entryId }) + return response.data + }) + }) + + entryCommand + .command("read") + .description("Get readability content") + .argument("<entryId>", "Entry ID") + .action(async function (this: Command, entryId: string) { + await runCommand(this, async ({ client }) => { + const response = await client.api.entries.readability({ id: entryId }) + return response.data + }) + }) + + entryCommand + .command("mark-read") + .description("Mark entry as read") + .argument("<entryId>", "Entry ID") + .action(async function (this: Command, entryId: string) { + await runCommand(this, async ({ client }) => { + const response = await client.api.reads.markAsRead({ entryIds: [entryId] }) + return response.data + }) + }) + + entryCommand + .command("mark-unread") + .description("Mark entry as unread") + .argument("<entryId>", "Entry ID") + .action(async function (this: Command, entryId: string) { + await runCommand(this, async ({ client }) => { + const response = await client.api.reads.markAsUnread({ entryId }) + return response.data + }) + }) + + entryCommand + .command("mark-all-read") + .description("Mark entries as read in current scope") + .option("--feed <feedId>", "Mark all entries in a feed as read") + .option("--list <listId>", "Mark all entries in a list as read") + .option("--view <type>", `View type: ${viewHelp}`, parseView) + .action(async function (this: Command, options: MarkAllReadOptions) { + await runCommand(this, async ({ client }) => { + if (options.feed && options.list) { + throw new CLIError("INVALID_ARGUMENT", "Use only one of --feed or --list.") + } + + const request: MarkAllAsReadRequest = { + feedId: options.feed, + listId: options.list, + view: options.view, + } + + const response = await client.api.reads.markAllAsRead(request) + return response.data + }) + }) +} diff --git a/apps/cli/src/commands/feed.ts b/apps/cli/src/commands/feed.ts new file mode 100644 index 000000000..2a6f55118 --- /dev/null +++ b/apps/cli/src/commands/feed.ts @@ -0,0 +1,44 @@ +import type { Command } from "commander" + +import { runCommand } from "../command" + +const isURL = (value: string) => value.startsWith("http://") || value.startsWith("https://") + +export const registerFeedCommand = (program: Command) => { + const feedCommand = program.command("feed").description("Manage feed data") + + feedCommand + .command("get") + .description("Get feed detail by feed ID or URL") + .argument("<feedIdOrUrl>", "Feed ID or URL") + .action(async function (this: Command, feedIdOrUrl: string) { + await runCommand(this, async ({ client }) => { + const response = await client.api.feeds.get( + isURL(feedIdOrUrl) ? { url: feedIdOrUrl } : { id: feedIdOrUrl }, + ) + return response.data + }) + }) + + feedCommand + .command("refresh") + .description("Refresh feed") + .argument("<feedId>", "Feed ID") + .action(async function (this: Command, feedId: string) { + await runCommand(this, async ({ client }) => { + const response = await client.api.feeds.refresh({ id: feedId }) + return response.data + }) + }) + + feedCommand + .command("analytics") + .description("Get feed analytics") + .argument("<feedId>", "Feed ID") + .action(async function (this: Command, feedId: string) { + await runCommand(this, async ({ client }) => { + const response = await client.api.feeds.analytics({ id: [feedId] }) + return response.data + }) + }) +} diff --git a/apps/cli/src/commands/list.ts b/apps/cli/src/commands/list.ts new file mode 100644 index 000000000..dd12e0c1e --- /dev/null +++ b/apps/cli/src/commands/list.ts @@ -0,0 +1,150 @@ +import type { Command } from "commander" + +import { parseNonNegativeInt, parseView, viewHelp } from "../args" +import { runCommand } from "../command" +import { CLIError } from "../output" + +interface ListCreateOptions { + title: string + description?: string + view?: number + fee?: number + image?: string +} + +interface ListUpdateOptions { + title?: string + description?: string + view?: number + fee?: number + image?: string +} + +interface ListFeedOptions { + feed: string +} + +export const registerListCommand = (program: Command) => { + const listCommand = program.command("list").description("Manage lists") + + listCommand + .command("ls") + .description("List my lists") + .action(async function (this: Command) { + await runCommand(this, async ({ client }) => { + const response = await client.api.lists.list({}) + return response.data + }) + }) + + listCommand + .command("get") + .description("Get list detail") + .argument("<listId>", "List ID") + .action(async function (this: Command, listId: string) { + await runCommand(this, async ({ client }) => { + const response = await client.api.lists.get({ listId }) + return response.data + }) + }) + + listCommand + .command("create") + .description("Create a list") + .requiredOption("--title <title>", "List title") + .option("--description <description>", "List description") + .option("--view <type>", `View type: ${viewHelp}`, parseView) + .option("--fee <amount>", "List fee", parseNonNegativeInt, 0) + .option("--image <url>", "List image URL") + .action(async function (this: Command, options: ListCreateOptions) { + await runCommand(this, async ({ client }) => { + const response = await client.api.lists.create({ + title: options.title, + description: options.description ?? null, + view: options.view ?? 0, + fee: options.fee ?? 0, + image: options.image ?? null, + }) + + return response.data + }) + }) + + listCommand + .command("update") + .description("Update a list") + .argument("<listId>", "List ID") + .option("--title <title>", "List title") + .option("--description <description>", "List description") + .option("--view <type>", `View type: ${viewHelp}`, parseView) + .option("--fee <amount>", "List fee", parseNonNegativeInt) + .option("--image <url>", "List image URL") + .action(async function (this: Command, listId: string, options: ListUpdateOptions) { + await runCommand(this, async ({ client }) => { + if ( + options.title === undefined && + options.description === undefined && + options.view === undefined && + options.fee === undefined && + options.image === undefined + ) { + throw new CLIError( + "INVALID_ARGUMENT", + "No update fields provided. Use at least one of --title, --description, --view, --fee, --image.", + ) + } + + const response = await client.api.lists.update({ + listId, + title: options.title, + description: options.description, + view: options.view, + fee: options.fee, + image: options.image, + }) + + return response.data + }) + }) + + listCommand + .command("delete") + .description("Delete a list") + .argument("<listId>", "List ID") + .action(async function (this: Command, listId: string) { + await runCommand(this, async ({ client }) => { + const response = await client.api.lists.delete({ listId }) + return response.data + }) + }) + + listCommand + .command("add-feed") + .description("Add feed to a list") + .argument("<listId>", "List ID") + .requiredOption("--feed <feedId>", "Feed ID") + .action(async function (this: Command, listId: string, options: ListFeedOptions) { + await runCommand(this, async ({ client }) => { + const response = await client.api.lists.addFeeds({ + listId, + feedId: options.feed, + }) + return response.data + }) + }) + + listCommand + .command("remove-feed") + .description("Remove feed from a list") + .argument("<listId>", "List ID") + .requiredOption("--feed <feedId>", "Feed ID") + .action(async function (this: Command, listId: string, options: ListFeedOptions) { + await runCommand(this, async ({ client }) => { + const response = await client.api.lists.removeFeed({ + listId, + feedId: options.feed, + }) + return response.data + }) + }) +} diff --git a/apps/cli/src/commands/opml.ts b/apps/cli/src/commands/opml.ts new file mode 100644 index 000000000..34baecde6 --- /dev/null +++ b/apps/cli/src/commands/opml.ts @@ -0,0 +1,84 @@ +import { mkdir, readFile, writeFile } from "node:fs/promises" + +import type { Command } from "commander" +import { basename, dirname } from "pathe" + +import { runCommand } from "../command" + +interface OpmlExportOptions { + output?: string +} + +interface OpmlImportOptions { + items?: string +} + +const parseItems = (value?: string): string[] => { + if (!value) { + return [] + } + + return value + .split(",") + .map((item) => item.trim()) + .filter((item) => item.length > 0) +} + +export const registerOPMLCommand = (program: Command) => { + const opmlCommand = program.command("opml").description("Import and export OPML") + + opmlCommand + .command("export") + .description("Export subscriptions as OPML") + .option("--output <file>", "Write exported OPML to file") + .action(async function (this: Command, options: OpmlExportOptions) { + await runCommand(this, async ({ client }) => { + const response = await client.api.subscriptions.export({ + format: "opml", + }) + + if (!options.output) { + return response + } + + await mkdir(dirname(options.output), { recursive: true }) + await writeFile(options.output, response.content, "utf8") + + return { + output: options.output, + filename: response.filename, + contentType: response.contentType, + bytes: Buffer.byteLength(response.content), + } + }) + }) + + opmlCommand + .command("import") + .description("Import subscriptions from OPML file") + .argument("<file>", "Path to OPML or XML file") + .option("--items <urls>", "Comma-separated feed URLs to import from parsed file") + .action(async function (this: Command, filePath: string, options: OpmlImportOptions) { + await runCommand(this, async ({ client }) => { + const fileBuffer = await readFile(filePath) + const fileName = basename(filePath) + const formData = new FormData() + + formData.append( + "file", + new Blob([fileBuffer], { + type: "application/octet-stream", + }), + fileName, + ) + + const items = parseItems(options.items) + if (items.length > 0) { + formData.append("items", JSON.stringify(items)) + } + + const response = await client.api.subscriptions.import(formData) + return response.data + }) + }) +} diff --git a/apps/cli/src/commands/search.ts b/apps/cli/src/commands/search.ts new file mode 100644 index 000000000..5566905ba --- /dev/null +++ b/apps/cli/src/commands/search.ts @@ -0,0 +1,111 @@ +import type { Command } from "commander" + +import { parsePositiveInt, parseView, viewHelp } from "../args" +import { runCommand } from "../command" + +type DiscoverTarget = "feeds" | "lists" +type TrendingRange = "1d" | "3d" | "7d" | "30d" +type TrendingLanguage = "eng" | "cmn" + +const parseDiscoverTarget = (value: string): DiscoverTarget => { + if (value === "feeds" || value === "lists") { + return value + } + throw new Error(`Invalid discover type "${value}". Use feeds or lists.`) +} + +const parseTrendingRange = (value: string): TrendingRange => { + if (value === "1d" || value === "3d" || value === "7d" || value === "30d") { + return value + } + throw new Error(`Invalid range "${value}". Use one of 1d, 3d, 7d, 30d.`) +} + +const parseTrendingLanguage = (value: string): TrendingLanguage => { + if (value === "eng" || value === "cmn") { + return value + } + throw new Error(`Invalid language "${value}". Use eng or cmn.`) +} + +interface SearchDiscoverOptions { + type?: DiscoverTarget +} + +interface SearchRsshubOptions { + lang?: string +} + +interface SearchTrendingOptions { + category?: string + range?: TrendingRange + view?: number + limit?: number + language?: TrendingLanguage +} + +export const registerSearchCommand = (program: Command) => { + const searchCommand = program.command("search").description("Discover feeds and lists") + + searchCommand + .command("discover") + .description("Discover feeds or lists") + .argument("<keyword>", "Search keyword") + .option("--type <type>", "Discover target: feeds | lists", parseDiscoverTarget) + .action(async function (this: Command, keyword: string, options: SearchDiscoverOptions) { + await runCommand(this, async ({ client }) => { + const response = await client.api.discover.discover({ + keyword, + target: options.type, + }) + return response.data + }) + }) + + searchCommand + .command("rsshub") + .description("Search RSSHub routes by category keyword") + .argument("<keyword>", "Category keyword") + .option("--lang <lang>", "Language tag") + .action(async function (this: Command, keyword: string, options: SearchRsshubOptions) { + await runCommand(this, async ({ client }) => { + const response = await client.api.discover.rsshub({ + categories: keyword, + lang: options.lang, + }) + return response.data + }) + }) + + searchCommand + .command("trending") + .description("Get trending feeds") + .option("--category <category>", "Filter by category keyword in title/description") + .option("--range <range>", "Trending range: 1d | 3d | 7d | 30d", parseTrendingRange, "7d") + .option("--view <type>", `View type: ${viewHelp}`, parseView) + .option("--limit <n>", "Result limit", parsePositiveInt, 20) + .option("--language <lang>", "Language: eng | cmn", parseTrendingLanguage) + .action(async function (this: Command, options: SearchTrendingOptions) { + await runCommand(this, async ({ client }) => { + const response = await client.api.trending.getFeeds({ + range: options.range, + view: options.view, + limit: options.limit, + language: options.language, + }) + + const keyword = options.category?.trim().toLowerCase() + const feeds = keyword + ? response.data.filter((item) => { + const title = item.feed.title?.toLowerCase() || "" + const description = item.feed.description?.toLowerCase() || "" + return title.includes(keyword) || description.includes(keyword) + }) + : response.data + + return { + feeds, + } + }) + }) +} diff --git a/apps/cli/src/commands/subscription.ts b/apps/cli/src/commands/subscription.ts new file mode 100644 index 000000000..13a224fb4 --- /dev/null +++ b/apps/cli/src/commands/subscription.ts @@ -0,0 +1,202 @@ +import type { + SubscriptionCreateRequest, + SubscriptionDeleteRequest, + SubscriptionUpdateRequest, +} from "@follow-app/client-sdk" +import type { Command } from "commander" + +import { parseView, viewHelp } from "../args" +import { runCommand } from "../command" +import { CLIError } from "../output" + +type SubscriptionTarget = "feed" | "list" | "url" +type UpdateTarget = "feed" | "list" + +const parseSubscriptionTarget = (value: string): SubscriptionTarget => { + if (value === "feed" || value === "list" || value === "url") { + return value + } + throw new Error(`Invalid target "${value}". Use feed, list, or url.`) +} + +const parseUpdateTarget = (value: string): UpdateTarget => { + if (value === "feed" || value === "list") { + return value + } + throw new Error(`Invalid target "${value}". Use feed or list.`) +} + +interface SubscriptionListOptions { + view?: number + category?: string +} + +interface SubscriptionAddOptions { + feed?: string + list?: string + category?: string + view?: number + private?: boolean + title?: string +} + +interface SubscriptionRemoveOptions { + target: SubscriptionTarget +} + +interface SubscriptionUpdateOptions { + category?: string + title?: string + view?: number + private?: boolean + public?: boolean + target: UpdateTarget +} + +export const registerSubscriptionCommand = (program: Command) => { + const subscriptionCommand = program.command("subscription").description("Manage subscriptions") + + subscriptionCommand + .command("list") + .description("List subscriptions") + .option("--view <type>", `View type: ${viewHelp}`, parseView) + .option("--category <name>", "Filter by category") + .action(async function (this: Command, options: SubscriptionListOptions) { + await runCommand(this, async ({ client }) => { + const response = await client.api.subscriptions.get( + options.view !== undefined ? { view: options.view } : {}, + ) + + const subscriptions = options.category + ? response.data.filter((item) => item.category === options.category) + : response.data + + return { + subscriptions, + } + }) + }) + + subscriptionCommand + .command("add") + .description("Add a feed or list subscription") + .option("--feed <url>", "Feed URL to subscribe") + .option("--list <listId>", "List ID to subscribe") + .option("--category <name>", "Subscription category") + .option("--view <type>", `View type: ${viewHelp}`, parseView) + .option("--private", "Mark subscription as private", false) + .option("--title <title>", "Custom subscription title") + .action(async function (this: Command, options: SubscriptionAddOptions) { + await runCommand(this, async ({ client }) => { + const selected = [options.feed, options.list].filter(Boolean) + if (selected.length !== 1) { + throw new CLIError("INVALID_ARGUMENT", "Use either --feed or --list when adding.") + } + + const request: SubscriptionCreateRequest = { + view: options.view ?? 0, + category: options.category ?? null, + isPrivate: options.private || false, + title: options.title ?? null, + } + + if (options.feed) { + request.url = options.feed + request.type = "feed" + } + + if (options.list) { + request.listId = options.list + request.type = "list" + } + + const response = await client.api.subscriptions.create(request) + return { + feed: response.feed, + list: response.list, + unread: response.unread, + } + }) + }) + + subscriptionCommand + .command("remove") + .description("Remove a subscription target") + .argument("<id>", "Feed ID, list ID, or feed URL") + .option( + "--target <target>", + "Subscription target type: feed | list | url", + parseSubscriptionTarget, + "feed", + ) + .action(async function (this: Command, id: string, options: SubscriptionRemoveOptions) { + await runCommand(this, async ({ client }) => { + const request: SubscriptionDeleteRequest = {} + + if (options.target === "feed") { + request.feedId = id + } else if (options.target === "list") { + request.listId = id + } else { + request.url = id + } + + const response = await client.api.subscriptions.delete(request) + return response.data + }) + }) + + subscriptionCommand + .command("update") + .description("Update a subscription target") + .argument("<id>", "Feed ID or list ID") + .option("--category <name>", "Set category") + .option("--title <title>", "Set custom title") + .option("--view <type>", `View type: ${viewHelp}`, parseView) + .option("--private", "Set subscription private", false) + .option("--public", "Set subscription public", false) + .option("--target <target>", "Target type: feed | list", parseUpdateTarget, "feed") + .action(async function (this: Command, id: string, options: SubscriptionUpdateOptions) { + await runCommand(this, async ({ client }) => { + if (options.private && options.public) { + throw new CLIError( + "INVALID_ARGUMENT", + "Use only one of --private or --public when updating.", + ) + } + + const request: SubscriptionUpdateRequest = { + category: options.category ?? undefined, + title: options.title ?? undefined, + view: options.view, + } + + if (options.private) { + request.isPrivate = true + } else if (options.public) { + request.isPrivate = false + } + + if (options.target === "feed") { + request.feedId = id + } else { + request.listId = id + } + + if ( + request.category === undefined && + request.title === undefined && + request.view === undefined && + request.isPrivate === undefined + ) { + throw new CLIError( + "INVALID_ARGUMENT", + "No update fields provided. Use at least one of --category, --title, --view, --private, --public.", + ) + } + + const response = await client.api.subscriptions.update(request) + return response.data + }) + }) +} diff --git a/apps/cli/src/commands/timeline.ts b/apps/cli/src/commands/timeline.ts new file mode 100644 index 000000000..c5fcdaab9 --- /dev/null +++ b/apps/cli/src/commands/timeline.ts @@ -0,0 +1,90 @@ +import type { EntryListRequest } from "@follow-app/client-sdk" +import type { Command } from "commander" + +import { parseISODate, parsePositiveInt, parseView, viewHelp } from "../args" +import { runCommand } from "../command" +import { CLIError } from "../output" + +type TimelineQuery = EntryListRequest & { + listId?: string +} + +interface TimelineOptions { + view?: number + limit: number + unreadOnly?: boolean + cursor?: string + feed?: string + list?: string + category?: string +} + +export const registerTimelineCommand = (program: Command) => { + program + .command("timeline") + .description("List timeline entries") + .option("--view <type>", `View type: ${viewHelp}`, parseView) + .option("--limit <n>", "Number of entries to fetch", parsePositiveInt, 20) + .option("--unread-only", "Only unread entries", false) + .option("--cursor <datetime>", "Pagination cursor (publishedAfter)", parseISODate) + .option("--feed <feedId>", "Filter timeline by feed") + .option("--list <listId>", "Filter timeline by list") + .option("--category <name>", "Filter timeline by subscription category") + .action(async function (this: Command, options: TimelineOptions) { + await runCommand(this, async ({ client }) => { + const scopedFilters = [options.feed, options.list, options.category].filter(Boolean) + if (scopedFilters.length > 1) { + throw new CLIError( + "INVALID_ARGUMENT", + "Use only one of --feed, --list, or --category at the same time.", + ) + } + + const query: TimelineQuery = { + limit: options.limit, + read: options.unreadOnly ? false : undefined, + view: options.view, + publishedAfter: options.cursor, + } + + if (options.feed) { + query.feedId = options.feed + } + + if (options.list) { + query.listId = options.list + } + + if (options.category) { + const subscriptions = await client.api.subscriptions.get( + options.view !== undefined ? { view: options.view } : {}, + ) + + const feedIdList = subscriptions.data + .filter((item) => item.category === options.category) + .map((item) => item.feedId) + .filter((item): item is string => item.length > 0) + + if (feedIdList.length === 0) { + return { + entries: [], + nextCursor: null, + hasNext: false, + } + } + + query.feedIdList = feedIdList + } + + const response = await client.api.entries.list(query) + const entries = response.data + const nextCursor = entries.at(-1)?.entries.publishedAt ?? null + + return { + entries, + nextCursor, + hasNext: Boolean(nextCursor) && entries.length >= options.limit, + } + }) + }) +} diff --git a/apps/cli/src/commands/unread.ts b/apps/cli/src/commands/unread.ts new file mode 100644 index 000000000..b32096fd0 --- /dev/null +++ b/apps/cli/src/commands/unread.ts @@ -0,0 +1,105 @@ +import type { + InboxSubscriptionResponse, + ListSubscriptionResponse, + SubscriptionWithFeed, +} from "@follow-app/client-sdk" +import type { Command } from "commander" + +import { parseView, viewHelp } from "../args" +import { runCommand } from "../command" + +interface UnreadListOptions { + view?: number +} + +const isInboxSubscription = ( + value: SubscriptionWithFeed | ListSubscriptionResponse | InboxSubscriptionResponse, +): value is InboxSubscriptionResponse => { + return "inboxes" in value +} + +const isListSubscription = ( + value: SubscriptionWithFeed | ListSubscriptionResponse | InboxSubscriptionResponse, +): value is ListSubscriptionResponse => { + return "lists" in value +} + +const resolveTitle = ( + value: SubscriptionWithFeed | ListSubscriptionResponse | InboxSubscriptionResponse, +): string | null => { + if (value.title) { + return value.title + } + if ("feeds" in value) { + return value.feeds.title ?? null + } + if ("lists" in value) { + return value.lists.title ?? null + } + if ("inboxes" in value) { + return value.inboxes.title ?? null + } + return null +} + +export const registerUnreadCommand = (program: Command) => { + const unreadCommand = program.command("unread").description("Unread status commands") + + unreadCommand + .command("count") + .description("Get total unread count") + .action(async function (this: Command) { + await runCommand(this, async ({ client }) => { + const response = await client.api.reads.getTotalCount() + return response.data + }) + }) + + unreadCommand + .command("list") + .description("List subscriptions with unread entries") + .option("--view <type>", `View type: ${viewHelp}`, parseView) + .action(async function (this: Command, options: UnreadListOptions) { + await runCommand(this, async ({ client }) => { + const [unreadResponse, subscriptionsResponse] = await Promise.all([ + client.api.reads.get(options.view !== undefined ? { view: options.view } : {}), + client.api.subscriptions.get(options.view !== undefined ? { view: options.view } : {}), + ]) + + const unreadMap = unreadResponse.data + const items = subscriptionsResponse.data + .map((subscription) => { + const unreadKey = isInboxSubscription(subscription) + ? subscription.inboxId + : subscription.feedId + const unreadCount = unreadMap[unreadKey] ?? 0 + + return { + sourceType: isInboxSubscription(subscription) + ? "inbox" + : isListSubscription(subscription) + ? "list" + : "feed", + sourceId: isInboxSubscription(subscription) + ? subscription.inboxId + : isListSubscription(subscription) + ? subscription.listId + : subscription.feedId, + feedId: subscription.feedId, + title: resolveTitle(subscription), + category: subscription.category ?? null, + view: subscription.view, + unreadCount, + isPrivate: subscription.isPrivate, + } + }) + .filter((item) => item.unreadCount > 0) + .sort((left, right) => right.unreadCount - left.unreadCount) + + return { + total: items.reduce((sum, item) => sum + item.unreadCount, 0), + items, + } + }) + }) +} diff --git a/apps/cli/src/config.ts b/apps/cli/src/config.ts new file mode 100644 index 000000000..cd91f94a2 --- /dev/null +++ b/apps/cli/src/config.ts @@ -0,0 +1,77 @@ +import { mkdir, readFile, writeFile } from "node:fs/promises" +import { homedir } from "node:os" + +import { join } from "pathe" + +export interface FoloCLIConfig { + token?: string + apiUrl?: string +} + +const configDir = join(homedir(), ".folo") +const configPath = join(configDir, "config.json") + +const normalizeConfig = (config: unknown): FoloCLIConfig => { + if (!config || typeof config !== "object") { + return {} + } + + const source = config as Record<string, unknown> + return { + token: typeof source.token === "string" ? source.token : undefined, + apiUrl: typeof source.apiUrl === "string" ? source.apiUrl : undefined, + } +} + +export const getConfigPath = () => configPath + +export const readConfig = async (): Promise<FoloCLIConfig> => { + try { + const raw = await readFile(configPath, "utf8") + return normalizeConfig(JSON.parse(raw)) + } catch (error) { + const nodeError = error as NodeJS.ErrnoException + if (nodeError.code === "ENOENT") { + return {} + } + + throw error + } +} + +const ensureConfigDir = async () => { + await mkdir(configDir, { recursive: true }) +} + +export const writeConfig = async (config: FoloCLIConfig) => { + await ensureConfigDir() + await writeFile(configPath, `${JSON.stringify(config, null, 2)}\n`, "utf8") +} + +export const updateConfig = async (patch: Partial<FoloCLIConfig>) => { + const current = await readConfig() + const next: FoloCLIConfig = { + ...current, + ...patch, + } + + if (!next.token) { + delete next.token + } + if (!next.apiUrl) { + delete next.apiUrl + } + + await writeConfig(next) + return next +} + +export const clearToken = async () => { + const current = await readConfig() + if (!current.token) { + return + } + + delete current.token + await writeConfig(current) +} diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.ts new file mode 100644 index 000000000..fa2089d97 --- /dev/null +++ b/apps/cli/src/index.ts @@ -0,0 +1,60 @@ +import { Command } from "commander" + +import { parseFormat } from "./args" +import { defaultApiURL } from "./client" +import { registerAuthCommand } from "./commands/auth" +import { registerCollectionCommand } from "./commands/collection" +import { registerEntryCommand } from "./commands/entry" +import { registerFeedCommand } from "./commands/feed" +import { registerListCommand } from "./commands/list" +import { registerOPMLCommand } from "./commands/opml" +import { registerSearchCommand } from "./commands/search" +import { registerSubscriptionCommand } from "./commands/subscription" +import { registerTimelineCommand } from "./commands/timeline" +import { registerUnreadCommand } from "./commands/unread" +import type { OutputFormat } from "./output" +import { normalizeError, printFailure } from "./output" + +const program = new Command() + +program + .name("folo") + .description("Folo CLI client for structured automation") + .version("0.1.0") + .option("-f, --format <format>", "Output format: json | table | plain", parseFormat, "json") + .option("--api-url <url>", `API base URL (default: ${defaultApiURL})`) + .option("--token <token>", "Override stored token") + .option("--verbose", "Enable verbose request/response logging", false) + +registerAuthCommand(program) +registerTimelineCommand(program) +registerSubscriptionCommand(program) +registerEntryCommand(program) +registerFeedCommand(program) +registerListCommand(program) +registerSearchCommand(program) +registerCollectionCommand(program) +registerOPMLCommand(program) +registerUnreadCommand(program) + +const resolveRequestedFormat = (argv: string[]): OutputFormat => { + for (let index = 0; index < argv.length; index += 1) { + const current = argv[index] + if ((current === "--format" || current === "-f") && argv[index + 1]) { + try { + return parseFormat(argv[index + 1]!) + } catch { + return "json" + } + } + } + return "json" +} + +try { + await program.parseAsync(process.argv) +} catch (error) { + const format = resolveRequestedFormat(process.argv) + printFailure(format, normalizeError(error)) + process.exitCode = 1 +} diff --git a/apps/cli/src/output.test.ts b/apps/cli/src/output.test.ts new file mode 100644 index 000000000..9bd4fbb96 --- /dev/null +++ b/apps/cli/src/output.test.ts @@ -0,0 +1,72 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" + +import { CLIError, normalizeError, printFailure, printSuccess } from "./output" + +describe("output helpers", () => { + beforeEach(() => { + vi.restoreAllMocks() + }) + + afterEach(() => { + vi.restoreAllMocks() + }) + + it("prints JSON success envelope", () => { + const infoSpy = vi.spyOn(console, "info").mockImplementation(() => {}) + + printSuccess("json", { value: 1 }) + + expect(infoSpy).toHaveBeenCalledTimes(1) + const payload = JSON.parse(infoSpy.mock.calls[0]![0] as string) as { + ok: boolean + data: { value: number } + error: null + } + expect(payload.ok).toBe(true) + expect(payload.data).toEqual({ value: 1 }) + expect(payload.error).toBeNull() + }) + + it("prints JSON failure envelope", () => { + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + + printFailure("json", { code: "E_TEST", message: "boom" }) + + expect(errorSpy).toHaveBeenCalledTimes(1) + const payload = JSON.parse(errorSpy.mock.calls[0]![0] as string) as { + ok: boolean + data: null + error: { code: string; message: string } + } + expect(payload.ok).toBe(false) + expect(payload.data).toBeNull() + expect(payload.error).toEqual({ code: "E_TEST", message: "boom" }) + }) + + it("prints ascii table in table mode", () => { + const infoSpy = vi.spyOn(console, "info").mockImplementation(() => {}) + + printSuccess("table", [{ id: "a", count: 1 }]) + + expect(infoSpy).toHaveBeenCalledTimes(1) + const output = infoSpy.mock.calls[0]![0] as string + expect(output).toContain("| id") + expect(output).toContain("| a") + }) + + it("normalizes CLIError", () => { + const normalized = normalizeError(new CLIError("E_CODE", "message")) + expect(normalized).toEqual({ + code: "E_CODE", + message: "message", + }) + }) + + it("normalizes generic Error", () => { + const normalized = normalizeError(new Error("generic")) + expect(normalized).toEqual({ + code: "UNKNOWN_ERROR", + message: "generic", + }) + }) +}) diff --git a/apps/cli/src/output.ts b/apps/cli/src/output.ts new file mode 100644 index 000000000..99e3878fb --- /dev/null +++ b/apps/cli/src/output.ts @@ -0,0 +1,192 @@ +import { inspect } from "node:util" + +import { FollowAPIError, FollowAuthError } from "@follow-app/client-sdk" + +export type OutputFormat = "json" | "table" | "plain" + +export interface OutputError { + code: string + message: string +} + +export class CLIError extends Error { + readonly code: string + + constructor(code: string, message: string) { + super(message) + this.name = "CLIError" + this.code = code + } +} + +const stringifyJSON = (value: unknown) => { + return JSON.stringify( + value, + (_key, currentValue) => { + if (typeof currentValue === "bigint") { + return currentValue.toString() + } + return currentValue + }, + 2, + ) +} + +const isRecord = (value: unknown): value is Record<string, unknown> => { + return typeof value === "object" && value !== null && !Array.isArray(value) +} + +const toCellValue = (value: unknown): string | number | boolean | null => { + if ( + value === null || + typeof value === "string" || + typeof value === "number" || + typeof value === "boolean" + ) { + return value as string | number | boolean | null + } + if (value === undefined) { + return "" + } + return stringifyJSON(value) +} + +const toTableRow = (value: unknown): Record<string, string | number | boolean | null> => { + if (!isRecord(value)) { + return { + value: toCellValue(value), + } + } + + const row: Record<string, string | number | boolean | null> = {} + for (const [key, currentValue] of Object.entries(value)) { + row[key] = toCellValue(currentValue) + } + return row +} + +const renderAsciiTable = ( + rows: Array<Record<string, string | number | boolean | null>>, +): string => { + if (rows.length === 0) { + return "(empty)" + } + + const columns = Array.from(new Set(rows.flatMap((row) => Object.keys(row)))) + const widths = columns.map((column) => + Math.max(column.length, ...rows.map((row) => String(row[column] ?? "").length)), + ) + + const formatLine = (values: string[]) => { + return `| ${values.map((value, index) => value.padEnd(widths[index]!)).join(" | ")} |` + } + + const border = `+-${widths.map((width) => "-".repeat(width)).join("-+-")}-+` + const header = formatLine(columns) + const body = rows.map((row) => formatLine(columns.map((column) => String(row[column] ?? "")))) + + return [border, header, border, ...body, border].join("\n") +} + +const renderTable = (data: unknown) => { + const rows = Array.isArray(data) ? data.map(toTableRow) : [toTableRow(data)] + console.info(renderAsciiTable(rows)) +} + +const renderPlain = (data: unknown) => { + if (Array.isArray(data)) { + console.info(data.map((item) => inspect(item, { depth: null, colors: false })).join("\n")) + return + } + + if (typeof data === "string") { + console.info(data) + return + } + + if (data === null || data === undefined) { + console.info("") + return + } + + console.info( + inspect(data, { + depth: null, + colors: false, + compact: false, + }), + ) +} + +export const printSuccess = (format: OutputFormat, data: unknown) => { + if (format === "json") { + const payload = { + ok: true as const, + data, + error: null, + } + console.info(stringifyJSON(payload)) + return + } + + if (format === "table") { + renderTable(data) + return + } + + renderPlain(data) +} + +export const printFailure = (format: OutputFormat, error: OutputError) => { + if (format === "json") { + const payload = { + ok: false as const, + data: null, + error, + } + console.error(stringifyJSON(payload)) + return + } + + console.error(`[${error.code}] ${error.message}`) +} + +const firstLine = (message: string) => { + const [head] = message.split("\n") + return head?.trim() || message +} + +export const normalizeError = (error: unknown, verbose = false): OutputError => { + if (error instanceof CLIError) { + return { + code: error.code, + message: error.message, + } + } + + if (error instanceof FollowAuthError) { + return { + code: "UNAUTHORIZED", + message: verbose ? error.message : firstLine(error.message), + } + } + + if (error instanceof FollowAPIError) { + return { + code: error.code ?? `HTTP_${error.status}`, + message: verbose ? error.message : firstLine(error.message), + } + } + + if (error instanceof Error) { + return { + code: "UNKNOWN_ERROR", + message: error.message, + } + } + + return { + code: "UNKNOWN_ERROR", + message: "An unknown error occurred", + } +} diff --git a/apps/cli/tsconfig.json b/apps/cli/tsconfig.json new file mode 100644 index 000000000..712036342 --- /dev/null +++ b/apps/cli/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "@follow/configs/tsconfig.extend.json", + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "lib": ["ES2022"], + "moduleResolution": "Bundler", + "types": ["node"], + "noEmit": true + }, + "include": ["src/**/*.ts", "tsup.config.ts"] +} diff --git a/apps/cli/tsup.config.ts b/apps/cli/tsup.config.ts new file mode 100644 index 000000000..62cb5de38 --- /dev/null +++ b/apps/cli/tsup.config.ts @@ -0,0 +1,16 @@ +import { defineConfig } from "tsup" + +export default defineConfig({ + entry: ["src/index.ts"], + format: ["esm"], + target: "node18", + outDir: "dist", + clean: true, + sourcemap: false, + dts: false, + splitting: false, + shims: false, + banner: { + js: "#!/usr/bin/env node", + }, +}) diff --git a/apps/cli/vitest.config.ts b/apps/cli/vitest.config.ts new file mode 100644 index 000000000..6e7b02531 --- /dev/null +++ b/apps/cli/vitest.config.ts @@ -0,0 +1,7 @@ +import { defineProject } from "vitest/config" + +export default defineProject({ + test: { + environment: "node", + }, +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ccca9fc14..d0265d723 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -185,6 +185,34 @@ importers: specifier: 3.2.4 version: 3.2.4(@edge-runtime/vm@3.2.0)(@types/debug@4.1.12)(@types/node@25.2.3)(happy-dom@20.6.1(bufferutil@4.1.0))(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2) + apps/cli: + dependencies: + '@follow-app/client-sdk': + specifier: 'catalog:' + version: 0.3.92(@opentelemetry/api@1.9.0)(better-sqlite3@12.6.2)(expo-sqlite@16.0.10(expo@54.0.33)(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(bufferutil@4.1.0)(react@19.1.0))(react@19.1.0))(hono@4.12.1)(kysely@0.28.11)(next@16.0.11(@babel/core@7.29.0)(@opentelemetry/api@1.9.0)(babel-plugin-react-compiler@1.0.0)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))(pg@8.16.3)(react-dom@19.1.0(react@19.1.0))(react@19.1.0) + commander: + specifier: 14.0.1 + version: 14.0.1 + pathe: + specifier: 2.0.3 + version: 2.0.3 + devDependencies: + '@follow/configs': + specifier: workspace:* + version: link:../../packages/configs + '@types/node': + specifier: 25.2.3 + version: 25.2.3 + tsup: + specifier: 8.5.0 + version: 8.5.0(jiti@2.6.1)(postcss@8.5.6)(tsx@4.21.0)(typescript@5.9.3)(yaml@2.8.2) + tsx: + specifier: 4.21.0 + version: 4.21.0 + typescript: + specifier: 'catalog:' + version: 5.9.3 + apps/desktop: devDependencies: '@electron-forge/cli': @@ -8991,6 +9019,12 @@ packages: resolution: {integrity: sha512-bkXY9WsVpY7CvMhKSR6pZilZu9Ln5WDrKVBUXf2S443etkmEO4V58heTecXcUIsNsi4Rx8JUO4NfX1IcQl4deg==} engines: {node: '>=18.20'} + bundle-require@5.1.0: + resolution: {integrity: sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + peerDependencies: + esbuild: '>=0.18' + bunyan@1.8.15: resolution: {integrity: sha512-0tECWShh6wUysgucJcBAoYegf3JJoZWibxdqhTm7OHPeT42qdjkZ29QCMcKwbgU1kiH+auSIasNRXMLWXafXig==} engines: {'0': node >=0.10.0} @@ -9362,6 +9396,10 @@ packages: resolution: {integrity: sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==} engines: {node: '>=18'} + commander@14.0.1: + resolution: {integrity: sha512-2JkV3gUZUVrbNA+1sjBOYLsMZ5cEEl8GTFP2a4AVz5hvasAMCQ1D2l2le/cX+pV4N6ZU17zjUahLpIXRrnWL8A==} + engines: {node: '>=20'} + commander@14.0.3: resolution: {integrity: sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==} engines: {node: '>=20'} @@ -11258,6 +11296,9 @@ packages: firebase@12.9.0: resolution: {integrity: sha512-CwwTYoqZg6KxygPOaaJqIc4aoLvo0RCRrXoln9GoxLE8QyAwTydBaSLGVlR4WPcuOgN3OEL0tJLT1H4IU/dv7w==} + fix-dts-default-cjs-exports@1.0.1: + resolution: {integrity: sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==} + flat-cache@4.0.1: resolution: {integrity: sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==} engines: {node: '>=16'} @@ -12307,6 +12348,10 @@ packages: react: optional: true + joycon@3.1.1: + resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==} + engines: {node: '>=10'} + jpeg-js@0.4.4: resolution: {integrity: sha512-WZzeDOEtTOBK4Mdsar0IqEU5sMr3vSV2RqkAIzUEV2BHnUfKGyswWFPFwK5EeDo93K3FohSHbLAjj0s1Wzd+dg==} @@ -12755,6 +12800,10 @@ packages: resolution: {integrity: sha512-3p6ZOGNbiX4CdvEd1VcE6yi78UrGNpjHO33noGwHCnT/o2fyllJDepsm8+mFFv/DvtwFHht5HIHSyOy5a+ChVQ==} engines: {node: '>=4'} + load-tsconfig@0.2.5: + resolution: {integrity: sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + loader-runner@4.3.1: resolution: {integrity: sha512-IWqP2SCPhyVFTBtRcgMHdzlf9ul25NwaFx4wCEH/KjAXuuHY4yNjvPXsBokp8jCB936PyWRaPKUNh8NvylLp2Q==} engines: {node: '>=6.11.5'} @@ -14210,6 +14259,24 @@ packages: ts-node: optional: true + postcss-load-config@6.0.1: + resolution: {integrity: sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==} + engines: {node: '>= 18'} + peerDependencies: + jiti: '>=1.21.0' + postcss: '>=8.0.9' + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + jiti: + optional: true + postcss: + optional: true + tsx: + optional: true + yaml: + optional: true + postcss-merge-longhand@7.0.5: resolution: {integrity: sha512-Kpu5v4Ys6QI59FxmxtNB/iHUVDn9Y9sYw66D6+SZoIk4QTz1prC4aYkhIESu+ieG1iylod1f8MILMs1Em3mmIw==} engines: {node: ^18.12.0 || ^20.9.0 || >=22.0} @@ -16569,6 +16636,25 @@ packages: tslib@2.8.1: resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + tsup@8.5.0: + resolution: {integrity: sha512-VmBp77lWNQq6PfuMqCHD3xWl22vEoWsKajkF8t+yMBawlUS8JzEI+vOVMeuNZIuMML8qXRizFKi9oD5glKQVcQ==} + engines: {node: '>=18'} + hasBin: true + peerDependencies: + '@microsoft/api-extractor': ^7.36.0 + '@swc/core': ^1 + postcss: ^8.4.12 + typescript: '>=4.5.0' + peerDependenciesMeta: + '@microsoft/api-extractor': + optional: true + '@swc/core': + optional: true + postcss: + optional: true + typescript: + optional: true + tsx@4.21.0: resolution: {integrity: sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==} engines: {node: '>=18.0.0'} @@ -21791,7 +21877,7 @@ snapshots: prettier-package-json: 2.8.0 prettier-plugin-autocorrect: 0.4.3(prettier@3.8.1) prettier-plugin-sh: 0.18.0(prettier@3.8.1) - prettier-plugin-tailwindcss: 0.6.14(@ianvs/prettier-plugin-sort-imports@4.4.2(prettier@3.6.2))(prettier@3.8.1) + prettier-plugin-tailwindcss: 0.6.14(@ianvs/prettier-plugin-sort-imports@4.4.2(prettier@3.8.1))(prettier@3.8.1) transitivePeerDependencies: - '@prettier/plugin-hermes' - '@prettier/plugin-oxc' @@ -26224,6 +26310,11 @@ snapshots: builtin-modules@5.0.0: {} + bundle-require@5.1.0(esbuild@0.25.12): + dependencies: + esbuild: 0.25.12 + load-tsconfig: 0.2.5 + bunyan@1.8.15: optionalDependencies: dtrace-provider: 0.8.8 @@ -26666,6 +26757,8 @@ snapshots: commander@12.1.0: {} + commander@14.0.1: {} + commander@14.0.3: {} commander@2.20.3: {} @@ -29338,6 +29431,12 @@ snapshots: transitivePeerDependencies: - '@react-native-async-storage/async-storage' + fix-dts-default-cjs-exports@1.0.1: + dependencies: + magic-string: 0.30.21 + mlly: 1.8.0 + rollup: 4.57.1 + flat-cache@4.0.1: dependencies: flatted: 3.3.3 @@ -30582,6 +30681,8 @@ snapshots: '@types/react': 19.1.17 react: 19.1.0 + joycon@3.1.1: {} + jpeg-js@0.4.4: {} js-cookie@3.0.5: {} @@ -30987,6 +31088,8 @@ snapshots: pify: 2.3.0 strip-bom: 3.0.0 + load-tsconfig@0.2.5: {} + loader-runner@4.3.1: {} local-pkg@0.5.1: @@ -32743,6 +32846,15 @@ snapshots: postcss: 8.5.6 ts-node: 10.9.2(@types/node@25.2.3)(typescript@5.9.3) + postcss-load-config@6.0.1(jiti@2.6.1)(postcss@8.5.6)(tsx@4.21.0)(yaml@2.8.2): + dependencies: + lilconfig: 3.1.3 + optionalDependencies: + jiti: 2.6.1 + postcss: 8.5.6 + tsx: 4.21.0 + yaml: 2.8.2 + postcss-merge-longhand@7.0.5(postcss@8.5.6): dependencies: postcss: 8.5.6 @@ -32970,7 +33082,7 @@ snapshots: prettier: 3.8.1 sh-syntax: 0.5.8 - prettier-plugin-tailwindcss@0.6.14(@ianvs/prettier-plugin-sort-imports@4.4.2(prettier@3.6.2))(prettier@3.8.1): + prettier-plugin-tailwindcss@0.6.14(@ianvs/prettier-plugin-sort-imports@4.4.2(prettier@3.8.1))(prettier@3.8.1): dependencies: prettier: 3.8.1 optionalDependencies: @@ -35222,6 +35334,34 @@ snapshots: tslib@2.8.1: {} + tsup@8.5.0(jiti@2.6.1)(postcss@8.5.6)(tsx@4.21.0)(typescript@5.9.3)(yaml@2.8.2): + dependencies: + bundle-require: 5.1.0(esbuild@0.25.12) + cac: 6.7.14 + chokidar: 4.0.3 + consola: 3.4.2 + debug: 4.4.3(supports-color@8.1.1) + esbuild: 0.25.12 + fix-dts-default-cjs-exports: 1.0.1 + joycon: 3.1.1 + picocolors: 1.1.1 + postcss-load-config: 6.0.1(jiti@2.6.1)(postcss@8.5.6)(tsx@4.21.0)(yaml@2.8.2) + resolve-from: 5.0.0 + rollup: 4.57.1 + source-map: 0.8.0-beta.0 + sucrase: 3.35.1 + tinyexec: 0.3.2 + tinyglobby: 0.2.15 + tree-kill: 1.2.2 + optionalDependencies: + postcss: 8.5.6 + typescript: 5.9.3 + transitivePeerDependencies: + - jiti + - supports-color + - tsx + - yaml + tsx@4.21.0: dependencies: esbuild: 0.27.3